This is correct behavior.1 In standards mode, body
, as well as html, doesn't immediately take up the entire height of the viewport, even though it appears so when you only apply a background to the latter. In fact, the html
element will take on the background of body
if you don't give it its own background, and html
will pass this on to the canvas:
根元素的背景成为画布的背景,并且其背景绘制区域延伸到覆盖整个画布,尽管任何图像的大小和位置都是相对于根元素的,就好像它们是单独为该元素绘制的一样。 (换句话说,背景定位区域是根据根元素确定的。)如果根元素的“background-color”值为“透明”,则画布的背景颜色取决于 UA。根元素不会再次绘制该背景,即其背景的使用值是透明的。
对于根元素是 HTML 的文档HTML
元素或 XHTMLhtml
元素:如果根元素上“background-image”的计算值为“none”并且其“background-color”为“transparent”,则用户代理必须从该元素的第一个 HTML 传播背景属性的计算值BODY
或 XHTMLbody
子元素。使用的值BODY
元素的背景属性是它们的初始值,传播的值被视为在根元素上指定。建议 HTML 文档的作者指定画布背景BODY
元素而不是HTML
元素。
不过,也就是说,您可以将任何背景图像叠加在单个元素的背景颜色上(或者html
or body
),无需依赖两个元素——只需使用background-color
and background-image
或将它们组合在background
简写属性:
body {
background: #ddd url(background.png) center top no-repeat;
}
如果你想合并两张背景图片,你需要依赖多个背景。主要有两天时间来做这件事:
-
在 CSS2 中,这就是两个元素的样式派上用场的地方:只需将背景图像设置为html
和另一张图片body
您希望将其叠加在第一个上。确保背景图像打开body
以全视口高度显示,您需要应用height
and min-height
分别还有:
html {
height: 100%;
background: #ddd url(background1.png) repeat;
}
body {
min-height: 100%;
background: transparent url(background2.png) center top no-repeat;
}
顺便说一句,你必须指定的原因height
and min-height
to html
and body
分别是因为这两个元素都没有任何固有高度。两者都是height: auto
默认情况下。它是具有 100% 高度的视口,所以height: 100%
从视口获取,然后应用于body
至少要允许内容滚动。
-
在 CSS3 中,语法已得到扩展,因此您可以在单个属性中声明多个背景值,无需将背景应用于多个元素(或调整height
/min-height
):
body {
background: url(background2.png) center top no-repeat,
#ddd url(background1.png) repeat;
}
唯一需要注意的是,在单个多层背景中,只有最底层可能有背景颜色。您可以在此示例中看到transparent
上层缺少值。
不用担心 - 即使您使用多层背景,上面指定的传播背景值的行为也完全相同。
不过,如果您需要支持较旧的浏览器,则需要使用 CSS2 方法,该方法一直支持到 IE7。
我的评论在这个另一个答案解释一下,并附上fiddle, how body
实际上是从html
默认情况下,即使它看起来像是被填充了,这又是由于这种看似奇怪的现象。
1 This may have its roots in setting the HTML background
and bgcolor
attributes of body
causing the background attribute to apply to the entire viewport. More on that here.