在整个页面上为主体赋予背景色.为什么? [英] Giving background-color to body applying whole page. Why?

查看:89
本文介绍了在整个页面上为主体赋予背景色.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

body {
  background-color: red;
}

<body>
  <div>Hello World!</div>
</body>

因此background-color: red;适用于整个页面的高度,但是当我检查页面时,主体的高度仅达到包含 Hello World!div.

So the background-color: red; applies to whole page height but when I inspect the page the height of the body is only up to the div containing Hello World!.

请有人解释为什么会这样.

Someone please explain this why it is happening like this.

推荐答案

主要原因是因为HTML采用BODYbackground-color,因为:

The main reason is because the HTML takes the background-color of BODY since:

根元素的背景变为 画布并覆盖整个画布[...]

The background of the root element becomes the background of the canvas and covers the entire canvas [...]

因此,由于HTML的默认background-colortransparent,它将采用BODY中的一个.但是,将颜色同时应用于HTMLBODY元素,您将看到BODY背景不再覆盖整个页面.

So since the default background-color of HTML is transparent it will take the one from BODY. However applying a color to both the HTML and BODY elements you will see that the BODY background doesn't cover the whole page anymore.

html {
  background-color: blue;
}

body {
  background-color: red;
}

<html>

<body>
  <div>Hello World!</div>
</body>

</html>

根元素的背景变为 画布并覆盖整个画布,锚定(用于 background-position)与如果 仅针对根元素本身进行绘制.根元素不 再次画这个背景.

The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for background-position) at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.

但是,对于HTML文档,我们建议作者指定 BODY元素而不是HTML元素的背景.为了 根元素是HTML"HTML"元素或XHTML的文档 计算值为transparent的"html"元素 background-colornone(对于background-image),用户代理必须 取而代之的是使用背景属性的计算值 元素的第一个HTML"BODY"元素或XHTML"body"元素子元素 为画布绘制背景,并且不得绘制背景 对于那个子元素.这样的背景还必须锚定在 与仅为根部绘制时相同的点 元素.

For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. 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. Such backgrounds must also be anchored at the same point as they would be if they were painted only for the root element.

来自 W3-14种颜色和背景./sub>

这篇关于在整个页面上为主体赋予背景色.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆