#parent {
background: pink;
}
#child {
width: 5000px;
}
<div id="parent">
<div id="child">Hello</div>
</div>
#parent
元素的粉红色背景不会持续存在于整个 #child
元素中。这是为什么?
在 body
元素上设置背景 does适用于整个 #child
,即使 #parent
和 body
共享相同的宽度,即视口(viewport)宽度。
奇怪的是,将#parent
元素的显示设置为inline-block
fixes这个问题,虽然我不知道为什么!
如有任何帮助,我们将不胜感激:)
最佳答案
The
#parent
's pink background doesn't persist across the entire#child
. Why is this?
这是因为 block 级元素的默认宽度为100%
.在本例中,它的宽度为 100%
的 body
元素,与视口(viewport)相同。
换句话说,即使元素的子元素的宽度为 5000px
, 它的宽度仍为 100%
无论视口(viewport)是什么,这意味着背景不会扩展到覆盖子元素。这不适用于 body
的原因元素是因为 body
元素是一个特例,the values are treated as if they were specified on the root element .见:
3.11.2. The Canvas Background and the HTML
<body>
ElementThe used values of that
body
element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element.
Curiously, setting the
#parent
display toinline-block
fixes this issue, though I have no idea why!
那是因为它不再是宽度为100%
的 block 级元素.另外,inline-block
元素有一个 "shrink-to-fit" width ,这意味着它们将采用子元素的宽度。同样添加display: table
会有类似的结果。
关于html - 为什么有背景的父元素不覆盖宽度大于视口(viewport)的子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34208677/