關於內層DIV設置margin-top不起作用的解決方案
(一)
近日在做另外一個站點的時候,又遇到這個問題,決定好好的研究解決一下。
代碼如下:
<div>上部層</div>
<div> <!--父層-->
<div style="margin-top:200px;">子層</div>
</div>
理想中的效果是父層和上部層貼邊顯示,子層距離父層頂部有200px的距離,在ie中正常,但是在ff中卻出現問題,子層和父層貼邊了,而父層和上部層卻間隔了200px。
百思不得其解,求助google,得到如下的一句:
當兩個容器嵌套時,如果外層容器和內層容器之間沒有別的元素,firefox會把內層元素的margin-top作用與父元素。
也就是說因為子層是父層的第一個非空子元素,所以使用margin-top會發生這個錯誤。
解決的辦法有兩個:
1、使用浮動來解決,即將子層代碼改為:<div style="margin-top:200px;float:left";>子層</div>
2、使用padding-top來解決,即:
<div style="padding-top:200px;">
<div>子層</div>
</div>
(二)
常常可以碰到這樣一個問題,就是外層DIV設置了高與寬,內層DIV如果設置maring-top不起作用(FIREFOX和IE8中測試),原因大致是內層div沒有獲得布局。如下面的代碼:
<style>
.aDiv {background:red; width:300px; height:300px; }
.bDiv {background:green; position:relative; width:100px; height:20px; margin-top:10px;}
.cDiv {background:black; position:relative; width:100px; height:20px;}
</style>
<div class="aDiv">
<div class="bDiv"></div>
<div class="cDiv"></div>
</div>
測試發現,bDiv的margin-top不起作用,仍是0px的顯示效果。如果在firefox中用firebug查看,可以看到margin-top是有值的,為10px;解決問題如下:
1、把margin-top改成padding-top,不過,前提是內層的Div沒有設置邊框
2、給外層的Div加padding-top
3、給外層DIV加:
A、float: left或right
B、position: absolute
C、display: inline-block或table-cell或其他 table 類型
D、overflow: hidden或auto
比如,可以更改上述代碼如下:
<style>
.a {background:red; width:300px; height:300px; float:left; }
.b {background:green; position:relative; width:100px; height:20px; margin:10px;}
.c {background:black; position:relative; width:100px; height:20px;}
.clear{ clear:both;}
</style>
<div class="a">
<div class="b"></div>
<div class="c"></div>
</div>
<div class="clear"></div>
注意:后面要加一個清除浮動。