為什麼設定的margin-top屬性不管用,margin-top不管用

來源:互聯網
上載者:User

為什麼設定的margin-top屬性不管用,margin-top不管用

為什麼設定的margin-top屬性不管用:
建議:儘可能的手寫代碼,可以有效提高學習效率和深度。
有時候大家可能會遇到奇怪的現象,儘管沒有任何的語法錯誤,但是設定的margin-top屬性不會起作用,下面就就結合代碼執行個體介紹一下產生此現象的原因和解決方案。
原因一:
外邊距合并margin-top屬性失效。代碼執行個體如下:

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="author" content="http://www.softwhy.com/" /><title>螞蟻部落</title><style type="text/css">.first{  width:100px;  height:100px;  background-color:red;  margin-bottom:60px;}.second{  width:100px;  height:100px;  background-color:green;  margin-top:40px;}</style></head><body><div class="first"></div><div class="second"></div></body></html>

從以上代碼的運行可以看出,第二個div設定的margin-top並沒有生效,起作用的是第一個div的設定的margin-bottom,這裡有個規律,那就是合并後的外邊距的高度等於外邊距的高度中的較大的一個,所以遇到此種情況可以格外注意外邊距大小的設定。
原因二:
子項目和父元素也可能會導致設定的子項目上外邊距失效情況,代碼執行個體如下:

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="author" content="http://www.softwhy.com/" /><title>螞蟻部落</title><style type="text/css">.father{  width:300px;  height:300px;  background-color:red;  margin-top:20px;}.children{  width:100px;  height:100px;  background-color:blue;  margin-top:10px;}</style></head><body><div class="father">  <div class="children"></div></div></body></html>

解決方案:
為父物件在相應的外邊距方向上有邊框(border)和內邊距(padding),或者為overflow屬性值設定為hidden即可避免。
IE6瀏覽器下不會出現外邊距合并現象。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=4638

更多內容可以參閱:http://www.softwhy.com/divcss/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.