為什麼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>為什麼margin-top不是作用於父元素</title><style type="text/css"> * { margin:0px; padding:0px; } p { width:100px; height:100px; background-color:green; margin-top:50px; } </style> </head> <body> <p></p> </body> </html>
以上代碼可以將p的上邊距設定為50px,一切運行良好,沒有任何問題,再來看下一段代碼:
<!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"> #parent { width:200px; height:200px; background-color:red; } #children { width:60px; height:60px; background-color:green; margin:0px auto; margin-top:50px; } </style> </head> <body> <p id="parent"> <p id="children"></p> </p> </body> </html>
以上代碼的初衷是讓子項目的頂部距離父元素50px,但是事實上卻並沒有實現預 期的效果,而是子項目頂部緊貼父元素,並且margin-top好像轉移給了父元素,讓父元素產生上外邊距。這其實是一個典型的外邊距合并問題,但是並非 所有的瀏覽器都會產生這種情況,一般標準瀏覽器都會出現此現象,而IE6和IE7在此狀態下不會出現外邊距合并現象。上外邊距合并出現的條件:
1.父元素的上邊距與子項目的上邊距之間沒有border。
2.父元素的上邊距與子項目的上邊距之間沒有非空內容。
3.父元素的上邊距與子項目的上邊距之間沒有padding。
3.父元素和子項目中沒有設定定位屬性(除static和relative)、overflow(除visible)和display:inline-block等。
4.父元素或者資源都沒有浮動。
注意:以上條件必須都要滿足才可以。那麼解決此中情況的方式也很簡單,只要破壞上面的一種情況就可以了。
更多關於外邊距合并內容可以參閱margin外邊距合并詳解一章節。