為什么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; } div { width:100px; height:100px; background-color:green; margin-top:50px; } </style> </head> <body> <div></div> </body> </html>
以上代碼可以將div的上邊距設置為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> <div id="parent"> <div id="children"></div> </div> </body> </html>
以上代碼的初衷是讓子元素的頂部距離父元素50px,但是事實上卻並沒有實現預 期的效果,而是子元素頂部緊貼父元素,並且margin-top好像轉移給了父元素,讓父元素產生上外邊距。這其實是一個典型的外邊距合並問題,但是並非 所有的瀏覽器都會產生這種情況,一般標准瀏覽器都會出現此現象,而IE6和IE7在此狀態下不會出現外邊距合並現象。上外邊距合並出現的條件:
1.父元素的上邊距與子元素的上邊距之間沒有border。
2.父元素的上邊距與子元素的上邊距之間沒有非空內容。
3.父元素的上邊距與子元素的上邊距之間沒有padding。
3.父元素和子元素中沒有設置定位屬性(除static和relative)、overflow(除visible)和display:inline-block等。
4.父元素或者資源都沒有浮動。
注意:以上條件必須都要滿足才可以。那么解決此中情況的方式也很簡單,只要破壞上面的一種情況就可以了。
更多關於外邊距合並內容可以參閱margin外邊距合並詳解一章節。
原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=4587
更多內容可以參閱:http://www.softwhy.com/divcss/