图解CSS - margin collapsing(外边距折叠)

有一种情况,设置子元素的 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

推荐阅读:

第3天 - Web UI 布局方式(二)Position

第2天 - Web UI 布局(一) 流式布局

图解前端

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值