margin塌陷问题的解决方式

在日常代码中出现的一个问题现象:
明明为子div中设置了margin-top的属性,但是并没有效果,反而,当子div的margin-top属性的值大于父div的margin-top的值的时候,整个结构往下移动,而不是子div与父div的顶端有margin距离。

<div class="wrapper">
	<div class="content"></div>
</div>  	

.wrapper {
	margin-left: 100px;
	margin-top: 100px;
	width: 100px;
	height: 100px;
	background-color: black;
}
.content {
	width: 50px;
	height: 50px;
	margin-top: 50px;
	margin-left: 50px;
	background-color: #00f;
}

在这里插入图片描述
此时,为父div设置属性border-top之后,子div成功地与父div有了margin距离,

<div class="wrapper">
	<div class="content"></div>
</div>  	

.wrapper {
	margin-left: 100px;
	margin-top: 100px;
	width: 100px;
	height: 100px;
	background-color: black;
	border-top: 1px solid #fff;
}
.content {
	width: 50px;
	height: 50px;
	margin-top: 50px;
	margin-left: 50px;
	background-color: #00f;
}

在这里插入图片描述
但是,这样地实现方法显然是不符合编码方式的。
于是,有以下方法可以来解决这个现象。改变盒子的语法规则。
为父div添加一下其中一个属性

overflow:hidden;
display:inline-block;
float: left;
position: absolute;
都能触发bfc,实现效果(下面是overflow的举例)
但是这些方法中没有所谓最优的方法,应该根据具体的需求去选择合适的方法来解决margin塌陷的BUG



.wrapper {
	margin-left: 100px;
	margin-top: 100px;
	width: 100px;
	height: 100px;
	background-color: black;
	overflow: hidden;
}
.content {
	width: 50px;
	height: 50px;
	margin-top: 50px;
	margin-left: 50px;
	background-color: #00f;
}

猜你喜欢

转载自blog.csdn.net/m0_38038767/article/details/88211259
今日推荐