CSS - 2个DIV之间的边缘碰撞

gio*_*ima 3 html css

我有两个DIV,我认为我有一个保证金碰撞......

<div style="margin-bottom: 10px;">Example box</div>
<div style="margin-top: 10px;">Example box</div>
Run Code Online (Sandbox Code Playgroud)

我之间有10px,我想要20px ..有什么建议吗?

Jos*_*ier 6

正如其他人已经说过的那样,这被称为崩溃边缘:

8箱型号 - 8.3.1折叠边距

在CSS中,两个或多个框(可能是也可能不是兄弟)的相邻边距可以组合形成单个边距.据说以这种方式组合的边距会崩溃,因此产生的合并边距称为折叠边距.

在这种情况下,他们是兄弟元素; 因此以下适用:

浮动框和任何其他框之间的边距不会崩溃(甚至在浮动及其流入子代之间也不会).

浮动其中一个兄弟元素会阻止边距折叠:

这里的例子

<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; float:left;">collapsing</div>
Run Code Online (Sandbox Code Playgroud)

内联块方框的边距不会崩溃(甚至不包括它们的流入子代).

制作元素inline-block还可以防止边距崩溃:

这里的例子

<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; display:inline-block;">collapsing</div>
Run Code Online (Sandbox Code Playgroud)

假设元素不是兄弟元素,您可以添加overflow:hidden到父元素,然后应用以下内容:

建立新块格式化上下文的元素的边距(例如浮点数和"溢出"除"可见"之外的元素)不会因其流入的子节点而崩溃.