元素水平垂直居中

元素水平垂直居中的4个方法总结。场景假设子元素在父元素中实现水平垂直

1
2
3
<div class="parent">
<div class="son"></div>
</div>

子元素固定宽高

  • 定位
1
2
.parent{width: 500px;height: 500px;border:2px solid #000;position:relative;}
.son{width: 200px;height: 200px;position: absolute;top: 50%;left:50%;margin-top:-100px;margin-left:-100px;}
  • 定位(也适用于不固定宽高内联元素,比如图片)
1
2
.parent{width: 500px;height: 500px;border:2px solid #000;position:relative;}
.son{width: 200px;height: 200px;position: absolute;top: 0;left:0;bottom:0;right:0;margin:auto;}
  • 父元素table-cell 方法
1
2
.parent{width: 500px;height: 500px;border:2px solid #000;text-align: center;display: table-cell;vertical-align: middle;}
.son{width: 200px;height: 200px; background: red;margin: auto;}

子元素不固定宽高

  • 定位 transform (兼容性ie10+)
1
2
.parent{width: 500px;height: 500px;border:2px solid #000;position:relative;}
.son{position: absolute;top: 50%;left:50%;transform: translate(-50%,-50%);}
  • 父元素table-cell 方法
1
2
.parent{width: 500px;height: 500px;border:2px solid #000;text-align: center;display: table-cell;vertical-align: middle;}
.son{ background: red;margin: auto;}
  • flex 方法
    1
    2
    3
    4
    5
    .parent {
    display: flex;
    align-items: center; //子元素垂直居中
    justify-content: center; //子元素水平居中
    }

附上 一篇详细介绍的文章