为什么 BODY 标签不覆盖 HTML 标签属性?

Why BODY tag doesn't override HTML tag properties?

我已将此 css 应用到我的 html 文档中:

html {
  background-color: red;
}

body {
  background-color: yellow;
}

并且页面背景变为 红色 而不是 黄色。 body 在 html 之后,所以它 必须覆盖 html 的红色。为什么没有发生? 提前致谢。

因为你的body是空的(0px高度)

如果我们改变body的h/w,你得到这个(包括margins/padding你可以重新设置)

html {
  background-color: red;
}

body {
  background-color: yellow;
  width: 100vw;
  height: 100vh;
}

含内容:

html {
  background-color: red;
}

body {
  background-color: yellow;
}
<h1>Body no longer empty</h1>

HTML 和 BODY 元素是不同的元素,因此级联规则(包括放置规则集的顺序)与此处无关。

你的困惑来源可能是因为 CSS 有一些 HTML 和 BODY 元素的 special rules:

For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element.

因此,如果您只设置其中 一个 ,那么这就是您将获得的颜色。

这里有一个红色 HTML 元素。

html { background: red; }

这里有一个黄色的 HTML 元素,因为它从 BODY 元素中提取了颜色。

body { background: yellow; }

但是,由于您设置了两者,所以这些特殊规则不适用。

HTML元素设置为红色BODY元素 设置为黄色。

您只是看不到它,因为您的 body 元素没有内容,因此计算出的高度为零。

html { background: red; }
body { background: yellow; }
<p>Hello, world.
<p>Since there is content in the body, it no longer has a zero height, so you can see its background.