css居中最佳实践

css居中是非常常见的问题,也是面试热门,现在对居中问题做个总结水平居中万能的text-align居中给父元素添加text-align: center,子元素都会居中,无论是inline还是block缺点:text-align属性会继承会影响后代元素display: table配合margin: 0 auto.center {display: table;margin: 0

css居中是非常常见的问题,也是面试热门,现在对居中问题做个总结

水平居中

万能的text-align居中

给父元素添加text-align: center,子元素都会居中,无论是inline还是block
缺点:text-align属性会继承会影响后代元素

display: table配合margin: 0 auto

.center {
display: table;
margin: 0 auto;
}
缺点:IE7以下不兼容,不过低版本IE微软自家都不支持了

垂直居中

line-height单行居中
line-height与height相等即可达到居中

.center{
height: 100px;
line-height: 100px;
}

display: table-cell配合vertical

父元素添加display: table,
子元素:

.child{
display: table-cell;
vertical-align: middle;
}
后两种都支持多行文字居中

综合解决方案

flexbox

给父元素设置display: flex;,水平居中用justify-content: center;,垂直居中设置align-items: center;

.parent{
display: flex;
justify-content: center;
align-items: center;
height: 400px;
}
缺点:兼容不是很好

绝对定位配合transform

父元素设置相对定位

.child{
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%, -50%);
}
缺点:低版本IE不兼容
同时这两种方案也解决了不定宽高居中的问题

参考资料

CSS居中完全指南
CSS之各种居中
Flex布局兼容性

关键字:css, flexbox, 居中, display