margin-top 實效問題

來源:互聯網
上載者:User

標籤:-name   51cto   解釋   作用   tracking   float   article   dev   dig   

 

文章出處:http://developer.51cto.com/art/201009/225816.htm

CSS屬性有很多值得學習的地方,你對CSS中margin-top屬性失效的解決方案是否熟悉,這裡和大家分享一下,相信通過本文的介紹你對margin-top屬性失效的解決方案一定會有深刻的認識。

關於margin-top屬性失效的解決方案

常出現兩種情況:

(一)margin-top失效

先看下面代碼:

  1. <div> 
  2. <divclassdivclass="box1">float:left</div> 
  3. <divclassdivclass="box2">clear:both;margin-top:20px;</div> 
  4. </div> 
  5.  

兩個層box1和box2,box1具有浮動屬性,box2沒有,這時候設定box2的上邊距margin-top沒有效果。

網上能找到的兩種比較靠譜的解釋:

1:“在CSS2.1中,水平的margin不會被摺疊;垂直margin可能在一些盒模型中被摺疊…”

2:當第一個層浮動,而第二個沒浮動層的margin會被壓縮,詳見--浮動元素後非浮動元素的margin的處理。

得到解決問題思路:要浮動一起浮動,要就一起不浮動。

解決辦法:

1.box2增加float屬性

2.box1與box2之間增加一層"<divstyle="clear:both;"></div>"

(二)子項目設定margin-top作用於父容器

  1. <divclassdivclass="box"style="height:100px;background:red;"> 
  2. <divclassdivclass="box2">clear:both;  
  3. margin-top:20px;height:50px;width:500px;  
  4. background:#000;</div> 
  5. </div> 
  6.  

當給box2設定margin-top時,在FF下僅作用於父容器。

解決辦法:

1.給父容器box加overflow:hidden;屬性

2.父容器box加border除none以外的屬性

3.用父容器box的padding-top代替margin-top

  

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.