1.如果要设置某个元素在窗体中水平垂直居中的话,将此元素设置为绝对定位(不设置其祖先为相对定位,让其默认针对窗体定位),然后设置元素的margin值为auto,在设置定位的上下左右都为0,即可实现此元素在窗体中水平垂直居中。
如:
margin:auto;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
如果要设置某个子元素在父元素中水平垂直居中的话,只要给父元素设置一个相对定位就可以了,子元素仍然和上面设置的一样。
如:
父元素{
position:relative;
}
子元素{
margin:auto;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}
2.可以通过定位具体的数值+负的margin值来实现水平垂直居中
流程如下: 先将子元素设置为绝对定位,然后top与left都设置为50%,然后margin就设置为负的宽高(可能会加上padding与border的值)的一半。【如何盒子的宽高为百分比的话,此种方法不在生效,margin-top的值不在是一半,而是1/4的样子】
注意:
a. 如果盒子模型是默认的w3c的盒子模型的话,那么请用宽高+padding+border的值,然后在除于2,作为负的margin值
#container{
width:200px;
height:200px;
padding:20px;
border:50px solid blue;
box-sizing:content-box; /* w3c盒子模型 */
position:absolute;
top:50%;
left:50%;
margin-left:-170px;/* (width+padding+border)/2 */
margin-top:-170px; /* (height+padding+border)/2 */
}
b. 如果盒子模型是ie6盒子模型的话,那么请直接用宽高的一半作为负的margin值
#container{
width:200px;
height:200px;
padding:20px;
border:50px solid blue;
box-sizing:border-box; /* ie6盒子模型 */
position:absolute;
top:50%;
left:50%;
margin-left:-100px;/* width/2 */
margin-top:-100px; /* height/2 */
}
3.使用flex布局实现水平垂直居中
流程如下:设置外层盒子为display:flex,然后在设置justify-content:center,aligin-items:center;即可。
display:flex;
justify-content:center;
align-items:center;