CSS background 属性
实例
在一个声明中设置不同的背景属性:
 
    body
 { 
background: lightblue url("img_tree.gif") no-repeat fixed center;
}
亲自试一试 »
background: lightblue url("img_tree.gif") no-repeat fixed center;
}
定义和用法
background 简写属性在一个声明中设置所有的背景属性。
可以设置如下属性:
- background-color
- background-image
- background-position
- background-size
- background-repeat
- background-origin
- background-clip
- background-attachment
如果不设置其中的某个值,也不会出问题,比如 background:#ff0000 url(smiley.gif); 也是允许的。
| 默认值: | 请参阅单独的属性 | 
|---|---|
| 继承性: | no | 
| 支持动画: | yes, 请参阅单独的属性. 阅读有关动画的信息 测试一下 | 
| 版本: | CSS1 + new properties in CSS3 | 
| JavaScript 语法: | object.style.background="red url(smiley.gif) top left no-repeat" 测试一下 | 
浏览器支持
表中的数字表示支持该属性的第一个浏览器版本。
| 属性 | |||||
|---|---|---|---|---|---|
| background | 1.0 | 4.0 | 1.0 | 1.0 | 3.5 | 
注释: 请参见下面每个值的单个浏览器支持。
语法
background: bg-color bg-image position/bg-size bg-repeat bg-origin bg-clip bg-attachment initial|inherit;
 
/* 使用 background-color */
background: green;
/* 使用 bg-imag> 和 repeat-style */
background: url("test.jpg") repeat-y;
/* 使用 box 和 background-color */
background: border-box red;
/* 将背景设为一张居中放大的图片 */
background: no-repeat center/80% url("../img/image.png");
background: green;
/* 使用 bg-imag> 和 repeat-style */
background: url("test.jpg") repeat-y;
/* 使用 box 和 background-color */
background: border-box red;
/* 将背景设为一张居中放大的图片 */
background: no-repeat center/80% url("../img/image.png");
background 属性被指定多个背景层时,使用逗号分隔每个背景层。
每一层的语法如下:
- 在每一层中,下列的值可以出现 0 次或 1 次:
  - <attachment>
- <bg-image>
- <position>
- <bg-size>
- <repeat-style>
 
- <bg-size>只能紧接着- <position>出现,以"/"分割,如: "- center/80%".
- <box>可能出现 0 次、1 次或 2 次。如果出现 1 次,它同时设定- background-origin和- background-clip。如果出现 2 次,第一次的出现设置- background-origin,第二次的出现设置- background-clip。
- <background-color>只能被包含在最后一层。
注意:  
background-color 只能在background的最后一个属性上定义,因为整个元素只有一种背景颜色。属性值
| 值 | 描述 | CSS | 
|---|---|---|
| background-color | 指定要使用的背景颜色 | 1 | 
| background-image | 指定要使用的一个或多个背景图像 | 1 | 
| background-position | 指定背景图像的位置 | 1 | 
| background-size | 指定背景图片的大小 | 3 | 
| background-repeat | 指定如何重复背景图像 | 1 | 
| background-origin | 指定背景图像的定位区域 | 3 | 
| background-clip | 指定背景图像的绘画区域 | 3 | 
| background-attachment | 设置背景图像是否固定或者随着页面的其余部分滚动。 | 1 | 
| initial | 将此属性设置为其默认值。请参阅 initial | 3 | 
| inherit | 从其父元素继承此属性。请参阅 inherit | 2 | 
相关页面
CSS 教程: CSS 背景, CSS 背景(高级)
HTML DOM 参考手册: background 属性
