有一种情况,设置子元素的 margin-top 后,发现子元素没有效果,父元素反而发生了偏移。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Margin collapsing</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: lightgray;
}
.div1 {
background-color: rebeccapurple;
height: 100px;
width: 100%;
}
.title {
margin-top: 20px;
background-color: antiquewhite;
line-height: 60px;
}
</style>
</head>
<body>
<div class="div1">
<div class="title">Margin collapsing</div>
</div>
</body>
</html>
上面的代码在 title 选择器中添加了 margin-top: 20px,结果发现并没有效果,反而父元素 div1 发生了移动。
这种情况称为 margin collapsing。
The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing.Note that the margins of floating and absolutely positioned elements never collapse.
上面的引用告诉我们,float 和 absolute 布局不会发生这种情况,解决办法,可以把 div1 改为(增加 position: absolute):
.div1 {
position: absolute;
background-color: rebeccapurple;
height: 100px;
width: 100%;
}
预览代码效果如下:
发生 margin collapsing 有 3 种情况:
1.相邻元素之间:相邻的两个元素之间的外边距会被折叠;
2.父元素与其第一个和最后一个元素之间,例子中就是这种情况,它会取父元素和子元素的 margin-top 最大值,前提是父元素和子元素都包含 margin-top 属性;
3.空的块级元素;
详细内容前往:
https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
推荐阅读:
图解前端