html - CSS - 2个DIV之间的边距冲突

标签 html css

我有两个 DIV,我想我有边距冲突...

<div style="margin-bottom: 10px;">Example box</div>
<div style="margin-top: 10px;">Example box</div>

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

最佳答案

正如其他人已经说过的,这被称为 collapsing margins :

8 Box model - 8.3.1 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.

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

Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).

float 其中一个兄弟元素将防止边距折叠:

EXAMPLE HERE

<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; float:left;">collapsing</div>

Margins of inline-block boxes do not collapse (not even with their in-flow children).

制作一个元素 inline-block 也可以防止边距折叠:

EXAMPLE HERE

<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; display:inline-block;">collapsing</div>

假设元素不是兄弟元素,您可以将 overflow:hidden 添加到父元素,因为以下内容将适用:

Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.

关于html - CSS - 2个DIV之间的边距冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21389187/

相关文章:

java - </br> 在 JTable 中

css - 为什么下面的 flexbox 大小奇怪(在 Chrome 40 中)?

javascript - 使用javascript在svg中设置动画半径

css - 带有仅包含图像的选择列表的 Bootstrap

javascript - 悬停时编辑按钮

html - Angular2,禁用 anchor 元素的正确方法是什么?

javascript - 我对 IE9 中的打印格式有疑问

html - 务实地定义通用外观和感觉的模板

css - 如何创建一个只有 1px 高度和其中图像的分区。没有任何边距和填充

javascript - div 位置 + 运算符无法按预期工作