我有两个 DIV 元素,我认为它们之间发生了外边距重叠...
<div style="margin-bottom: 10px;">Example box</div>
<div style="margin-top: 10px;">Example box</div>
我之前他们之间有10像素的间距,现在想要20像素的间距。有什么建议吗?
在这种情况下,它们是兄弟元素;因此,以下适用:在CSS中,两个或多个框的相邻边距(可能是兄弟,也可能不是)可以组合形成单个边距。以这种方式组合的边距被称为折叠边距,并且生成的组合边距称为折叠边距。
将其中一个兄弟元素浮动将防止边距折叠:浮动框与任何其他框之间的边距不会折叠(甚至不会在浮动和其内流子元素之间折叠)。
<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; float:left;">collapsing</div>
行内块级框的边距不会发生折叠(即使与其流动的子元素也不会)。
将元素设置为inline-block
也可以防止边距折叠:
<div style="margin-bottom: 10px;">These are NOT</div>
<div style="margin-top: 10px; display:inline-block;">collapsing</div>
overflow:hidden
添加到父元素中,因为这样就会应用以下规则:
建立新的块格式化上下文的元素(如浮动元素和具有“overflow”属性但非“visible”的元素)的边距不会与其内部流元素的边距合并。
<div style="margin-bottom: 10px; display: inline-block;">Example box</div>
<div style="margin-top:10px;">Example box</div>
<div style="margin-bottom: 20px;">Example box</div>
<div>Example box</div>
只需为第一个 div 添加 20px 的边距:
<div style="margin-bottom: 20px;">Example box</div>
<div>Example box</div>
padding
而不是 margin。 - DaniP