谁能解释为什么在内部 div 的边缘空间中最外层的 div 中没有显示背景颜色?
<div style="background-color:yellow;">
<div style="margin-top:10px;background-color:black;color:white;">
Why isn't the background color yellow inside my top margin?
</div>
</div>
谁能解释为什么在内部 div 的边缘空间中最外层的 div 中没有显示背景颜色?
<div style="background-color:yellow;">
<div style="margin-top:10px;background-color:black;color:white;">
Why isn't the background color yellow inside my top margin?
</div>
</div>
div 是块元素,但它们本身不占用空间(除了创建换行符),因此您的内部 div 填充了外部 div 内的所有可用空间,掩盖了黄色背景。向最外层的 div 添加一些填充,您将看到黄色。
这被称为“保证金崩溃”。
在 CSS 中,两个或多个框(可能是或可能不是兄弟)的相邻边距可以组合形成一个边距。以这种方式组合的边距称为折叠边距,由此产生的组合边距称为折叠边距。
正如在其他答案中发现的那样,向父级添加padding
或border
将防止边距折叠。
根据此处描述的 tarkabak 方法,我还成功地将以下 CSS 应用于容器。(请注意和的有限浏览器兼容性。):before
:after
.prevent-margin-collapse:before,
.prevent-margin-collapse:after
{
content: "\00a0"; /* No-break space character */
display: block;
overflow: hidden;
height: 0;
}
<div style="background-color:yellow;" class="prevent-margin-collapse">
<div style="margin-top:10px;background-color:black;color:white;">
Why isn't the background color yellow inside my top margin?
</div>
</div>
为了实现你想要看到的改变你的 html 如下:
<div style="background-color:yellow; padding-top:10px;">
<div style="background-color:black;color:white;">
Why isn't the background color yellow inside my top margin?
</div>
</div>
原因是外部 div 没有设置宽度,只取其内容的大小。
我想这与不从其他地方继承任何属性有关。
<div style="background-color:yellow; position: fixed;">
<div style="margin-top:10px;background-color:black;color:white;">
Why isn't the background color yellow inside my top margin?
</div>
</div>