CSS垂直居中,你会多少种写法?

来源 | https://wintc.top/article/4
一、水平居中
块级元素 设置width,并设置margin auto 内联元素 父元素设置text-align center
1、块级元素水平居中
.container {height: 300px;width: 300px;border: 1px solid red;}.content {width: 10rem;border: 1px solid green;margin: 0 auto;}
效果:

2、内联元素水平居中
.container {height: 300px;width: 300px;border: 1px solid red;text-align: center;}.content {display: inline-block;border: 1px solid green;}

二、水平垂直居中
1、flex布局
display: flexalign-items: center
如果同时要水平居中,则同时设置:justify-content center ,需要注意的是IE10+才支持,webkit前缀浏览器设置flex属性需要加webkit。
{width: 300px;height: 300px;border: 1px solid red;display: -webkit-flex;display: flex;关键属性: center; // 垂直居中: center // 水平居中}{border: 1px solid green;}
效果:

2、 margin+ position:absolute布局
.container {width: 300px;height: 300px;position: relative;border: 1px solid red;}.content {position: absolute;left: 0;right: 0;top: 0;bottom: 0;width: 200px;height: 100px;margin: auto;border: 1px solid green;}

3、 transform + absolute
.container {width: 300px;height: 300px;position: relative;border: 1px solid red;}.content {position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);border: 1px solid green;}
效果:

这个方法有个小缺陷,就是translate函数的参数,最后的计算值不能为小数,否则有的浏览器渲染出来效果会模糊,所以使用本方法的话最好设置一下宽高为偶数。
4、absolute+margin负值
代码:
.container {width: 300px;height: 300px;position: relative;border: 1px solid red;}.content {position: absolute;left: 50%;top: 50%;width: 200px;height: 100px;margin-top: -50px;margin-left: -100px;border: 1px solid green;}

5、absolute + calc
.container {width: 300px;height: 300px;border: 1px solid red;text-align: center;position: relative;}.content {position: absolute;border: 1px solid green;width: 200px;height: 100px;left: calc(50% - 100px);top: calc(50% - 50px);}

6、 line-height + vertical-align
代码:
.container {width: 300px;height: 300px;border: 1px solid red;line-height: 300px;text-align: center;}.content {display: inline-block;line-height: 1.5;border: 1px solid green;vertical-align: middle;}



评论
