CSS中的background属性允许您控制任何元素的背景。它也有一个速记属性,这意味着它允许您在一行中编写多个背景属性值。像这样:
body {
background:
url(sweettexture.jpg) /* image */
top center / 200px 200px /* position / size */
no-repeat /* repeat */
fixed /* attachment */
padding-box /* origin */
content-box /* clip */
red; /* color */
}
背景由八个其他属性组成:
- background-image
- background-position
- background-size
- background-repeat
- background-attachment
- background-origin
- background-clip
- background-color
您几乎可以按任何顺序使用您喜欢的这些属性的任意组合(尽管规范中推荐的顺序如上所述)。但是有一个问题:在background属性中未指定的任何内容都会自动设置为默认值。所以如果你做这样的事情:
body {
background-color: red;
background: url(sweettexture.jpg);
}
但结果背景是透明的,而不是红色。修复很简单:只需把background-color定义放在background之后即可,或只使用速记(例如background: url(...) red;)
多个背景
CSS3增加了对多个背景的支持,这些背景层堆叠在彼此的顶部。与背景相关的任何属性都可以使用逗号分隔开,如下所示:
body {
background: url(sweettexture.jpg), url(texture2.jpg) black;
background-repeat: repeat-x, no-repeat;
}
逗号分隔列表中的每个值对应一个图层:第一个值是顶层,第二个值是第二个图层,背景颜色始终是最后一个图层。