例子中html代码如下:
<div class="center"></div>
为了让结果更清晰加上如下的css样式
.center{
width:100px;
height: 100px;
background-color: gray;
}
1. 实现水平居中
1) margin: 0 auto——IE6-8,chrome和mozilla测试有效
这是常用的方法,该方法兼容IE6-8,chrome和mozilla
2) 父元素设置text-align: center——但是该方法只适用于IE6,IE7
例如设置:
body{
text-align: cenert;
}
3) 利用position:absolute和margin——IE6-8,chrome和mozilla测试有效
.center{
position: absolute;
left: 50%;
margin-left: -50%;
}
这里用left:50%使div的左边界距离窗口50%,但是需要向左移动50%的width(div本身的宽度)才能真正实现水平居中;
也可以替换left和margin-left:
.center{
position: absolute;
margin-left: 50%;
left: -50px;
}
2. 实现水平垂直居中
1) 利用position: absolute和margin:auto——兼容IE8,chrome和mozilla,但是不兼容IE6-7
.center{
position: absolute;
top:0;
bottom:0;
left:0;
right:0;
margin: auto;
}
可能有人认为利用margin: 0 auto可以实现水平居中, 那么margin: auto 0和margin: auto可以分别实现垂直居中和水平垂直居中,但是其实是错误的。前者无法实现居中,而后者也只能实现水平居中。但是配合position: absolute就能实现水平垂直居中。
2) 利用position: absolute和margin——IE6-8,chrome和mozilla测试有效
.center{
position: absolute;
left: 50%;
margin-left: -50px;
left: 50%;
margin-left: -50px;
}
<div class="container">
<div class="center"></div>
</div>
css:
.container{
width:500px;
height:500px;
background:yellow;
display: flex;
}
.center{
width:100px;
height:100px;
background:gray;
margin:auto
}