在web页面布局中,居中是很常见的问题,针对不同的情况,使用居中的方法也不同,最近在网上看了大量的文章,博客,总结出了一些常用且好用的方法。
之前统一设置了父元素:
.parent1,.parent2,.parent3,.parent4,.parent5,.parent6{
height:300px;
width:600px;
background:#f00;
}
加上颜色为了区分
1.子元素定宽(兼容性ie8+)
<div class="parent1">
<div class="son1">定宽水平垂直居中</div>
</div>
.parent1{
display: table-cell;
vertical-align: middle;
}
.son1{
width:150px;
margin:0 auto;
background: #0f0;
}
或者(兼容低版本ie)
.parent1{
position: relative;
}
.son1{
width:150px;
height:50px;
background: #0f0;
position: absolute;
left:50%;top:50%;
margin:-25px 0 0 -75px;
}
2.子元素不定宽(兼容性ie8+)
<div class="parent2">
<div class="son2">不定宽水平垂直居中</div>
</div>
.parent2{
display: table-cell;
vertical-align: middle;
}
.son2{
display: table;
margin:0 auto;
background: #0f0;
}
区别在于,子元素使用display:table;这样子元素将以最小宽度展现
3.浮动元素水平垂直居中(兼容性ie8+)
<div class="parent3">
<div class="son3-p">
<div class="son3">浮动元素水平垂直居中</div>
</div>
</div>
这里注意,为了实现居中效果,在本需要居中的.son3前加了一层div,然后
.parent3{
display: table-cell;
vertical-align: middle;
margin:0 auto;
}
.son3-p{
float:left;
position: relative;
left:50%;
}
.son3{
float:left;
background: #0f0;
position: relative;
left:-50%;
}
4.绝对定位实现水平垂直居中(兼容性ie8+)常用于图片居中
<div class="parent4">
<div class="son4">绝对定位实现水平垂直居中 ie8+</div>
</div>
.parent4{
position: relative;
}
.son4{
height:100px;
width:200px;
background: #0f0;
position: absolute;
top:0;right:0;bottom:0;left:0;
margin:auto;
}
5.flex实现水平垂直居中(ie9+)
<div class="parent5">
<div class="son5">flex实现水平垂直居中</div>
</div>
.parent5{
display:flex;
}
.son5{
background: #0f0;
margin:auto;
}
6.transform实现水平垂直居中(ie9+)
<span style="color:#000000;"> <div class="parent6">
<div class="son6">transform实现水平垂直居中</div>
</div></span>
<span style="color:#000000;"> .son6{
background: #0f0;
position: relative;
width:200px;
height:50px;
top:50%;left:50%;
transform:translate(-50%,-50%);
}</span>