自学内容网 自学内容网

【CSS】margin塌陷和margin合并及其解决方案

【CSS】margin塌陷和margin合并及其解决方案

一、解决margin塌陷的问题

问题:当父元素包裹着一个子元素的时候,当给子元素设置margin-top:100px,此时不应该看到的是子元素距离父元素顶部100px嘛?为什么是父元素距离body100px?
原因父元素与子元素之间,给子元素添加margin-top属性时,此时只是想让子元素的边框距离父元素边框有一段距离,而却出现了父元素的顶端距离body这个边框出现了位移,这就是margin-top塌陷的现象。

.container{
height: 300px;
width: 300px;
background-color: blue;
/* overflow: hidden; */
}
.box {
background: red;
height: 100px;
width: 100px;
margin-top: 50px;
}
<div class="container">
<div class="box">
</div>
</div>

在这里插入图片描述

解决方案:给父元素添加overflow:hidden触发BFC;

.container{
height: 300px;
width: 300px;
background-color: blue;
    overflow: hidden; 
}

在这里插入图片描述

二、避免外边距margin重叠(margin合并)

问题:两个兄弟块元素,一个设置下外边距100px,一个设置上外边距100px,此时它们不应该是相距200px才对嘛?为什么只相距了100px?
原因兄弟之间的元素,垂直方向的margin-bottom和margin-top会合并为单个边距,其大小为单个边距的最大值,如果值一样则值仅为其中一个。这就是外边距重叠现象。

.box {
background: red;
height: 100px;
width: 100px;
}
<div class="box" style="margin-bottom: 100px;">
</div>
<div class="box" style="margin-top: 100px;">
</div>

在这里插入图片描述
解决办法每个元素放置不同的BFC中,通过overflow: hidden;触发BFC

.container {
overflow: hidden;
}
.box {
background: red;
height: 100px;
width: 100px;
}
<div class="container">
<div class="box" style="margin-bottom: 100px;">
</div>
</div>
<div class="container">
<div class="box" style="margin-top: 100px;">
</div>
</div>

在这里插入图片描述


原文地址:https://blog.csdn.net/m0_61049675/article/details/136044768

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!