问题描述
浮动元素导致的后面img标签居中对齐“失败”,如下图
<div>
<div class="content1">
<div class="float-left">left-div</div>
<div class="float-right">right-div</div>
</div>
<div class="content2">
<img src="./1.jpg" style="width:150px;height:150px;"/>
<p>center text</p>
</div>
</div><style>
.content1{
background: pink;
height:50px;
line-height:50px;
}
.float-left{
float: left;
width: 100px;
height: 50px;
background: tan;
}
.float-right{
float: right;
width: 100px;
height: 51px;
background: tan;
}
.content2{
background:springgreen;
text-align:center;
height: 300px;
}
</style>
问题原因
浮动元素造成的影响,文本、行内元素、行内块元素会采取环绕的方式排列在浮动元素周围。图中right-div的高度为51px,高于父级div的50px,故img标签居中是相对于
(父级div宽度)-(right-div宽度)
来计算的,所以偏离了正常水平居中的位置。若将p标签放到第img标签前面去,则不会产生这种问题。但最好的办法还是清除浮动
。
清除浮动的方法
clear:both
-
使用
<div style="clear:both"></div>
-
使用
伪元素
,结果与上面方式2一致,未能解决问题.clearfix:before,
.clearfix:after{
content: '';
display: table;
clear: both;
}
.clearfix: { zoom:1 } //触发IE的haslayout.
BFC(Block formatting context)
- 设置content1样式
overflow:hidden
,完美解决问题
总结:总而言之,本次问题是由于浮动和设置了浮动元素父级元素高度共同作用的结果,不是仅仅清除浮动就能完全解决的。若不设置浮动元素父元素的高度,则img也会正常垂直居中,但浮动未清除。若只清除浮动,而不解决高度突出的问题,则img不能正常垂直居中。设置
overflow:hidden
刚好两点都做到了。
参考文章:清除浮动方法解析