margin-top 不生效的原因和解決方法


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

  (2012-04-06 10:56:35)
嵌套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="width:300px; height:100px">上部層</div>

<div style=" width:300px; height:300px;overflow:hidden "> <!--父層-->
     <div style="margin:50px; 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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM