為什麼設定的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/