CSS(margin)問題巢狀div中margin-top轉移

xiaoyuyyun發表於2014-10-09
http://www.w3school.com.cn/css/css_margin_collapsing.asp
原因:盒子沒有獲得 haslayout  造成 margin-top無效
這個是常見的外邊距合併問題
margin疊加了,你給外邊的盒子一個border或者padding就好了,這個叫空白邊疊加,
巢狀div中margin-top轉移問題的解決辦法

 在這兩個瀏覽器中,有兩個巢狀關係的div,如果外層div的父元素padding值為0,那麼內層div的margin-top或者margin-bottom的值會“轉移”給外層div。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html xmlns="http://www.w3.org/1999/xhtml">
< head>
< meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
< title>無標題文件</title>
< /head>

< body>
< div style="background-color:#FF0000;width:300px; height:100px">上部層</div>

< div style="background-color:#009900; width:300px; height:300px;overflow:hidden "> <!--父層-->
      <div style="margin:50px; background-color:#000000;width:200px; height:200px"">子層</div>
< /div>

< /body>
< /html>

原因:盒子沒有獲得 haslayout  造成 margin-top無效
 
解決辦法:
1、在父層div加上:overflow:hidden;
2、把margin-top外邊距改成padding-top內邊距 ;
3、父元素產生邊距重疊的邊有不為 0 的 padding 或寬度不為 0 且 style 不為 none 的 border。
    父層div加: padding-top: 1px;
 4、讓父元素生成一個 block formating context,以下屬性可以實現
    * float: left/right
     * position: absolute
     * display: inline-block/table-cell(或其他 table 型別)
     * overflow: hidden/auto
    父層div加:position: absolute;

相關文章