什么是父子级元素外边距合并问题?
父子级元素外边距问题就是原本给子元素设置了margin-top,结果连带父元素也一起往下移,例如:
<style>
.father{
width: 200px;
height: 200px;
background-color: red;
}
.son{
width: 50px;
height: 50px;
background-color: blue;
margin-top: 100px;
}
</style>
...
<div class="father">
<div class="son"></div>
</div>
如上图,给子元素设置margin-top后,不是子元素往下移,而是父元素也一起下来,感觉就像是把margin-top设置给了父元素,这就是父子级元素外边距合并问题。
解决方法:
1.给父元素设置边框
在父元素style标签内设置border: 1px solid;
结果如下:
2.给父元素或子元素设置浮动属性
在父元素或子元素的style标签内设置float: left;
结果与上图一样。
3.给父元素或子元素设置绝对定位属性
在父元素或子元素的style标签内设置position: absolute;/position: fixed;
4.给父元素设置overflow: hidden属性
在父元素style标签内设置overflow: hidden;
5.给父元素或子元素设置display: inline-block属性
在父元素或子元素的style标签内设置display: inline-block;
6.把原本设置给子元素的margin-top的值设置给父元素的padding-top
在父元素style标签内设置padding-top: 100px;
但是如果父元素是标准盒子,该方法会改变父元素的大小。