css 基础捡漏(三) margin塌陷 margin合并 BFC 及相关解决办法

看下面的例子,你会发现father距上方100px,而child并没有离父元素上方100px.这就是margin塌陷

而father和mather间距也不是150px,而是100px,这就是margin合并

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>BFC</title>
	<style>
		*{
			padding: 0;
			margin: 0;
		}
		.father{
			width: 300px;
			height: 300px;
			margin-top: 50px;
			background-color: yellow;
			margin-bottom: 100px;
		}
		.child{
			width: 200px;
			height: 200px;
			background-color: red;
			margin-top: 100px;
		}
		.mather{
			width: 300px;
			height: 300px;
			margin-top: 50px;
			background-color: blue;
		}
	</style>
</head>
<body>
	<div class="father">
		<div class="child"></div>
	</div>
	<div class="mather"></div>
</body>
</html>
  • margin塌陷:父子元素,垂直方向的margin会取较大值

触发一个元素的BFC,即可以解决margin塌陷的问题

BFC:会改变盒子内的渲染规则,但仅仅非常小的一部分会改变。

触发BFC的条件:

  1. position: absolute;
  2. display: inline-block;
  3. float: left/right;
  4. overflow: hidden;

根据需要去选择对其他元素影响最小的条件,在这里father上加上overflow: hidden;即可。

  • margin合并:兄弟元素,垂直方向上下margin会合并,取较大值

同样可以触发其父元素的BFC,但为了对各元素的影响最小,一般只设置margin-top或margin-bottom,将其设置大点即可

发布了53 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/bingqise5193/article/details/101208649