middle

单行文本水平&垂直居中

div {
line-height:200;
height:200;
text-align:center;
}

仅居中元素定宽高适用

- absolute + 负margin
- absolute + margin auto
- absolute + calc

居中元素不定宽高

- absolute + transform
- line-height
- writing-mode
- table
- css-table
- flex
- grid
<div class="wp">
    <div class="box size">123123</div>
</div>

absolute + 负margin

absolute + margin auto

absolute + calc

absolute + transform

line-height

writing-mode

table

css-table

flex

grid

总结

  • PC端有兼容性要求,宽高固定,推荐absolute + 负margin

  • PC端有兼容要求,宽高不固定,推荐css-table

  • PC端无兼容性要求,推荐flex

  • 移动端推荐使用flex

方法
居中元素定宽高固定
PC兼容性
移动端兼容性

absolute + 负margin

ie6+, chrome4+, firefox2+

安卓2.3+, iOS6+

absolute + margin auto

ie6+, chrome4+, firefox2+

安卓2.3+, iOS6+

absolute + calc

ie9+, chrome19+, firefox4+

安卓4.4+, iOS6+

absolute + transform

ie9+, chrome4+, firefox3.5+

安卓3+, iOS6+

writing-mode

ie6+, chrome4+, firefox3.5+

安卓2.3+, iOS5.1+

line-height

ie6+, chrome4+, firefox2+

安卓2.3+, iOS6+

table

ie6+, chrome4+, firefox2+

安卓2.3+, iOS6+

css-table

ie8+, chrome4+, firefox2+

安卓2.3+, iOS6+

flex

ie10+, chrome4+, firefox2+

安卓2.3+, iOS6+

grid

ie10+, chrome57+, firefox52+

安卓6+, iOS10.3+

Last updated