day4-margin塌陷问题

131 阅读1分钟

我正在参加「掘金·启航计划」

问题表述

当父元素未设置边框、没有margin和padding的时候(即子元素紧贴着父元素的上边界)给子元素设置margin-top,父盒子会跟着一起掉下来。

<head>
	<meta charset="utf-8">
	<title></title>
	<style>
		.father {
			width: 200px;
			height: 200px;
			background-color: aquamarine;
		}
		
		.son {
			width: 100px;
			height: 100px;
			background-color: orange;
			margin-top: 50px;
		}
	</style>
</head>

<body>
	<div class="father">
		<div class="son"></div>
	</div>
</body>

如下图所示:

微信截图_20221031233241(1).png

这是因为父子嵌套元素在垂直方向上的margin,是结合在一起的,他们两个的margi会取其中最大的值,父元素为0,子元素为50。父元素的margin-top自然变成了50px。

margin塌陷解决办法:

1.给父元素设置边框或内边距padding

.father {
	width: 200px;
	height: 200px;
	background-color: aquamarine;
	border-top: 5px solid black; /* 父元素加边框 */
}

.father {
	width: 200px;
	height: 200px;
	background-color: aquamarine;
	padding-top: 20px; /* 父元素加padding */
}

微信截图_20221031233934.png 微信截图_20221031234311.png

虽然能解决塌陷问题,但是整个元素高度发生变化,需要变动的地方、牵扯的可能会很多。不推荐使用

2.触发BFC改变元素渲染方式。

触发BFC后,特定的元素会遵循另一套渲染规则,以解决margin塌陷问题。用到overflow:hidden;就可以解决。

.father {
	width: 200px;
	height: 200px;
	background-color: aquamarine;
	overflow: hidden;
}

微信截图_20221031234749.png 这就是一开始想要的样子。