实现DIV盒子水平垂直居中的方法有很多,在这里将主要介绍几种常用的。
-
flex:在父容器上设置,让主轴和侧轴的子元素排列方式都为center
//父容器 display:flex; justify-content:center; align-items:center;
-
position:子绝父相,margin设置为auto;top/right/bottom/left的值都设置为0
//父容器 position:relative; //子容器 position:absolute; margin:auto; top:0; right:0; bottom:0; left:0;
-
position+transform:子绝父相,子盒子top、left都50%,再transform:translate(-50%,-50%)
//父容器 position:relative; //子容器 position:absolute; top:50%; left:50%; transform:translate(-50%,-50%)
-
子绝父相,子盒子top、left都50%,再margin-top、margin-left是当前盒子宽度一半的负值;
//父容器 position:relative; //子容器 position:absolute; width: 600px; height: 600px; left: 50%; top: 50%; margin-left: -300px; margin-top: -300px;
以上几种方式推荐使用弹性盒子,因为在使用定位的时候会使元素脱离文档流出现撑不起父盒子的问题,而在弹性盒子中不会出现这样的问题。