浮动元素致使的后面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标签前面去,则不会产生这种问题。但最好的办法仍是清除浮动
。
使用<div style="clear:both"></div>
spring
使用伪元素
,结果与上面方式2一致,未能解决问题spa
.clearfix:before, .clearfix:after{ content: ''; display: table; clear: both; } .clearfix: { zoom:1 } //触发IE的haslayout.
overflow:hidden
,完美解决问题
总结:总而言之,本次问题是因为浮动和设置了浮动元素父级元素高度共同做用的结果,不是仅仅清除浮动就能彻底解决的。若不设置浮动元素父元素的高度,则img也会正常垂直居中,但浮动未清除。若只清除浮动,而不解决高度突出的问题,则img不能正常垂直居中。设置
overflow:hidden
恰好两点都作到了。
参考文章:清除浮动方法解析code