父元素與子項目之間的margin-top問題

來源:互聯網
上載者:User
給子項目盒子一個垂直外邊距margin-top,父元素盒子也會往下走margin-top的值,遇到此問題的朋友可以參考下本文或許會有意想不到的收穫 hack
父元素的盒子包含一個子項目盒子,給子項目盒子一個垂直外邊距margin-top,父元素盒子也會往下走margin-top的值,而子項目和父元素的邊距則沒有發生變化。

html代碼

代碼如下:

<p class="box1">
<p class="box2"></p>
</p>

css樣式

代碼如下:

.box1{height:200px;width:200px;background:gray;}
.box2{height:100px;width:100px;background:gold;margin-top:50px;}


解決方案
1、修改父元素的高度,增加padding-top樣式類比(padding-top:1px;常用)
2、為父元素添加overflow:hidden;樣式即可(完美)
3、為父元素或者子項目聲明浮動(float:left;可用)
4、為父元素添加border(border:1px solid transparent可用)
5、為父元素或者子項目聲明絕對位置

相關文章

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.