CSS 增删边框 为什么会导致 位置移动?可能是因为子元素的 margin!
今天使用 CSS 遇到了一个神奇的问题:去掉一个仅 1px 粗的边框(border),竟能使整个元素远距离地移动。
先来看看复现结果:一个 div
包裹着另一个 div
。
外面的命名为 wrapper
、里面的命名为 content
吧。
外面的加了边框,里面的设置了巨大的 margin-top
(60px)。
为了看清楚,还给 wrapper
设置了高度和背景颜色。
<html>
<head>
<title>TEST</title>
</head>
<body style="margin: 0;">
<div id="wrapper">
<div id="content">some thing ...</div>
</div>
<style>
#wrapper {
border: red 1px solid;
background-color: lime;
height: 180px;
}
#content {
margin-top: 60px;
}
</style>
</body>
</html>
那么,如果把 wrapper
的红色边框去掉,会有什么效果?对比如下:
去掉边框后,里面的 content 仍然距离顶部有 60px;然而,外面的 wrapper 掉下来了。
进一步修改 content
的 margin-top
可以证实,那一块空白的高度对应的就是这个 margin-top
。
令人非常难以理解……
一、【content
的 margin】为什么与【wrapper
是否有边框】有关?
找到了一点点线索:CSS 标准中提到,多个 margins 可以 坍塌/融合。
链接:CSS Box model : collapsing margins
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin.
Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
随后还详细定义了什么是 adjoining 、列出了 collapse 的条件……太复杂了就没仔细去读(但里面提到了 border)。
不知道与我们这个现象有没有关系?
二、为什么外层 wrapper
会掉下来?
如果按上面的解释,两者共用了一个 margin-top,那 wrapper
也就无中生有地获得了一个 margin、然后被挤下来了?
不知道这样理解对不对。