子項目應該margin-top為何會影響父元素【轉】

來源:互聯網
上載者:User

標籤:

這個問題困惑了很久,雖然沒有大礙早就摸出來怎麼搞定它,但始終不明白原因出在哪裡,如果只是IE有問題我也不會太在意,可問題是所有上等瀏覽器都表現如此,這樣叫我怎能安心?今天總算下狠心查出來怎麼回事,居然是CSS2.1盒模型規範……雖然很彆扭,非常彆扭的規定。   問題如,兩層Div結構,Outer Div屬性為“margin:0 auto”,本該緊貼外框頂部的,如果沒有Inner Div,或者沒有Inner Div的“margin-top”屬性,一切如預期。但是當Inner Div設定了“margin-top:10px”之後,它的父元素Outer Div也被撐出來一個本不該有的“margin-top:10px”效果。


Inner Div [margin-top: 10px]
Outer Div [margin: 0 auto]
 HTML Demo Area

 這個“問題”……它是CSS2.1的盒模型中規定的內容——Collapsing margins:

In this specification, the expression  collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin. 所有毗鄰的兩個或更多盒元素的margin將會合并為一個margin共用之。毗鄰的定義為:同級或者嵌套的盒元素,並且它們之間沒有非空內容、Padding或Border分隔。

  這就是原因了。“嵌套”的盒元素也算“毗鄰”,也會 Collapsing Margins。這個合并Margin其實很常見,就是文章段落元素<p/>,並列很多個的時候,每一個都有上下1em的margin,但相鄰的<p/>之間只會顯示1em的間隔而不是相加的2em。這個很好理解,我就是奇怪為什麼W3C要讓嵌套的元素也共用Margin,想不出來在什麼情況下需要這樣的表現。   這個問題的避免方法很多,只要破壞它出現的條件就行。給 Outer Div 加上 padding/border,或者給 Outer Div / Inner Div 設定為 float/position:absolute(CSS2.1規定浮動元素和絕對位置元素不參與Margin摺疊)。   更多資訊,關於不同值的margin摺疊後表現的計算方法等等,可自行查閱W3C的CSS2.1規範:Collapsing margins。

http://blog.csdn.net/duran1986/article/details/6930967

 html部分代碼

<body><div  class="div1"><div class="div2"></div></div></body>

 

出問題的代碼

        html,html body {            margin: 0;            padding: 0;            border: 0;        }        .div1 {            height: 100px;            background-color: red;        }        .div2 {            height: 20px;            background-color: green;            margin-top: 80px;        }

 

已經解決問題的代碼

        html,html body {            margin: 0;            padding: 0;            border: 0;        }        .div1 {            height: 100px;            background-color: red;            position: absolute;            width: 100%;        }        .div2 {            height: 20px;            background-color: green;            margin-top: 80px;            width: 100%;        }

 

子項目應該margin-top為何會影響父元素【轉】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.