css中 margin塌陷的问题

现象:如下代码

<div class="wrapper">
	<div class="content"></div>
</div>
.wrapper{
	width: 200px;
	height: 200px;
	background: #aaa;
	margin-left:200px ;
	margin-top:200px ;	
}
.content{
	width: 100px;
	height: 100px;
	background: #234;
}

然后,如果我们现在要给深蓝色的子级div添加margin外边距

先添加左边的,如下所示,并没有问题

.content{
	width: 100px;
	height: 100px;
	background: #234;
	margin-left: 20px;
}

再添加小盒子的上外边距,如下,并没有效果,而且这里如果我们把margin-top设置的太大了,会导致整个大盒子一起向下移动

.content{
	width: 100px;
	height: 100px;
	background: #234;
	margin-top: 50px;
}

如上所描述的就是margin塌陷问题了

既然有问题了就很定会有解决的办法,下面介绍两种,第一种太残暴了,不推荐使用,应该是禁止使用。但是作为一种解决办法,在这里也记录一下

第一种,添加上边框,给外边的盒子添加一个上边框就能解决

border-top: 1px solid #fff;

下面说一下正经的解决办法,就是通过BFC

首先简单了解一下什么是BFC

BFC : 块级格式化上下文 (Block Fromatting Context)

W3C对BFC的定义如下:浮动元素和绝对定位元素,非块级盒子的块级容器(例如 inline-blocks, table-cells, 和 table-captions),以及overflow值不为“visiable”的块级盒子,都会为他们的内容创建新的BFC(块级格式上下文)。

用父盒子触发BFC就能解决margin塌陷问题

那触发BFC的条件有哪些呢?

(1) position:absolute;
(2) display:inline-block;
(3) float: left/right;
(4) overflow: hidden; 溢出隐藏

将如上触发条件中的一条放到父容器中就能触发,从而解决margin塌陷问题,如

.wrapper{
	width: 200px;
	height: 200px;
	background: #aaa;
	margin-left:200px ;
	margin-top:200px ;	
	position: absolute;
}

除了margin塌陷外还有margin合并问题

我在这里贴个链接,刚看了一下介绍的还不错

https://blog.csdn.net/qq_32381815/article/details/78987828

猜你喜欢

转载自blog.csdn.net/qq_39125684/article/details/81589578