css中clear與margin的相互作用
lear與margin的相互作用
1. clear與margin的重疊
請看如下程式碼:
1.<div style="background-color:#f5f5f5;">
<imgsrc="http://img.mukewang.com/53d60af3000171a002560191.jpg"style="float:left;">
<div style="clear:both;margin-bottom:100px;">clear:both;</div>
</div>
<divstyle="margin-top:100px;">本文字離圖片的距離是100px</div>
<br><br><br><br>
2.<divstyle="background-color: #f5f5f5; overflow: hidden;">
<imgsrc="http://img.mukewang.com/53d60af3000171a002560191.jpg"style="float:left; margin-bottom: 100px;">
</div>
<div style="margin-top:100px;">本文字離圖片的距離是200px</div>
在上面程式碼中,第一段文字裡圖片的距離是100px
第二段文字裡圖片的距離是200px
分析:浮動會使父元素高度塌陷,第一個大的div裡設定clear:both屬性的元素(即使小div)的垂直方向上的margin會消失,與clear重疊了。 而第二個大div則margin正常顯示。
2. clear使margin-top的失效
請看如下程式碼:
<divstyle="float:left;">float:left</div>
<div style="clear:both;margin-top:100px;margin-left:100px;background:red;margin-right: 100px;">clear:both</div>
在這段程式碼中第二個div中的margin-top會失效。
在浮動元素後的第一個元素如果設定了clear:left(both也行),那麼這個元素的margin-top將會失效