關於內層DIV設定margin-top不起作用的解決方案

來源:互聯網
上載者:User
(一)

近日在做另外一個網站的時候,又遇到這個問題,決定好好的研究解決一下。

代碼如下:

<p>上部層</p>

<p> <!--父層-->
<p style="margin-top:200px;">子層</p>
</p>

理想中的效果是父層和上部層貼邊顯示,子層距離父層頂部有200px的距離,在ie中正常,但是在ff中卻出現問題,子層和父層貼邊了,而父層和上部層卻間隔了200px。

百思不得其解,求助google,得到如下的一句:

當兩個容器嵌套時,如果外層容器和內層容器之間沒有別的元素,firefox會把內層元素的margin-top作用與父元素。

也就是說因為子層是父層的第一個非空子項目,所以使用margin-top會發生這個錯誤。

解決的辦法有兩個:

1、使用浮動來解決,即將子層代碼改為:<p style="margin-top:200px;float:left";>子層</p>

2、使用padding-top來解決,即:

<p style="padding-top:200px;">
<p>子層</p>
</p>

(二)

常常可以碰到這樣一個問題,就是外層p設定了高與寬,內層p如果設定maring-top不起作用(FIREFOX和IE8中測試),原因大致是內層p沒有獲得布局。如下面的代碼:

<style>

.ap {background:red; width:300px; height:300px; }
.bp {background:green; position:relative; width:100px; height:20px; margin-top:10px;}
.cp {background:black; position:relative; width:100px; height:20px;}
</style>

<p class="ap">
<p class="bp"></p>
<p class="cp"></p>
</p>

測試發現,bp的margin-top不起作用,仍是0px的顯示效果。如果在firefox中用firebug查看,可以看到margin-top是有值的,為10px;解決問題如下:

1、把margin-top改成padding-top,不過,前提是內層的p沒有設定邊框
2、給外層的p加padding-top
3、給外層p加:

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>

<p class="a">
<p class="b"></p>
<p class="c"></p>
</p>

<p class="clear"></p>

注意:後面要加一個清除浮動。

相關文章

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.