微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

应用背景和/或

http://jsfiddle.net/julien_c/GmAL4/

我发现,如果你应用CSS背景的身体,它占据整个页面(无论实际的身高或身高的宽度)。

但是,如果将CSS背景应用于html和body,则body的背景不占用整个页面

这种差异是否预期的行为?

如何叠加两个全屏背景(例如,背景颜色和半透明图像?)

解决方法

这是 correct behavior.1身体不立即占用视口的整个高度,即使它出现,所以当你只应用背景的后者。事实上,如果你不给它自己的背景,html元素将占据body的背景,html将把这个传递给视口:

The background of the root element becomes the background of the canvas and its background painting area extends to cover the entire canvas,although any images are sized and positioned relative to the root element as if they were painted for that element alone. (In other words,the background positioning area is determined as for the root element.) If the root’s ‘background-color’ value is ‘transparent’,the canvas’s background color is UA dependent. The root element does not paint this background again,i.e.,the used value of its background is transparent.

For documents whose root element is an HTML HTML element or an XHTML html element: if the computed value of ‘background-image’ on the root element is ‘none’ and its ‘background-color’ is ‘transparent’,user agents must instead propagate the computed values of the background properties from that element’s first HTML BODY or XHTML body child 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. It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

尽管如此,但是,你可以将任何背景图像叠加在单个元素(html或body)上的背景颜色上,而不必依赖于两个元素 – 只需使用背景颜色和背景图像或将它们组合在背景中属性

body {
    background: #ddd url(background.png) center top no-repeat;
}

如果你想结合两个背景图片,你需要依靠多个背景。主要有两天这样做:

>在CSS2中,这是样式的两个元素派上用场:简单地设置一个背景图像为HTML和另一个图像到你想叠加在第一个的身体。要确保在完整视口高度下身体显示的背景图像,您还需要分别应用height和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和min-height到html和body的原因是因为这两个元素都没有任何固有的高度。两者都是height:认为auto。它是具有100%高度的视口,因此高度:100%从视口获取,然后应用于身体作为最小允许滚动内容
>在CSS3中,语法已经扩展,所以你可以declare multiple background values in a single property,消除需要应用背景到多个元素(或调整高度/最小高度):

body {
    background: url(background2.png) center top no-repeat,#ddd url(background1.png) repeat;
}

唯一的警告是,在单个多层背景中,只有最底层可以具有背景颜色。您可以在此示例中看到透明值从上层丢失。

不要担心 – 上面指定的具有传播背景值的行为即使使用多层背景也能工作完全相同。

如果你需要支持旧的浏览器,你需要使用CSS2方法,这是支持一直回到IE7。

我在this other answer下的意见解释,伴随着fiddle,身体如何实际上从html偏移认边距,即使它看起来像是被填补了,再次由于这个看似奇怪的现象。

1这可能有其根在设置HTML背景和bgcolor身体的属性导致背景属性应用于整个视口。更多关于here

原文地址:https://www.jb51.cc/css/221267.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。