html - 为什么有背景的父元素不覆盖宽度大于视口(viewport)的子元素?

标签 html css

this simple HTML :

#parent {
  background: pink;
}

#child {
  width: 5000px;
}
<div id="parent">
  <div id="child">Hello</div>
</div>

#parent 元素的粉红色背景不会持续存在于整个 #child 元素中。这是为什么?

body 元素上设置背景 does适用于整个 #child,即使 #parentbody 共享相同的宽度,即视口(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> Element

The 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 to inline-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/

相关文章:

asp.net - 尝试使用 vbscript 显示 SQL 数据库中的数据

javascript - 背景图片不显示有问题

html - 如何将图标对齐到 div 元素内的中心?

javascript - 播放视频时背景变暗

css - 如何在全屏桌面 View 中隐藏 fontawesome 图标

CSS:将图像 Sprite 与 css 伪类 :before 和 :after 结合使用

html - IE8 和 IE9 中的背景位置底部不起作用

html - 忽略悬停对象

html - 顶部导航栏中元素的高度随着 Logo 高度的增加而增加

html - 如何溢出 3 级深度菜单 ul > li > ul > li > ul > li