div嵌套引起的margin-top不起作用

嵌套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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章