background

background 是一种 CSS 简写属性,用于一次性集中定义各种背景属性,包括 color, image, origin 与 size, repeat 方式等等。

尝试一下

此属性是一个 简写属性,可以在一次声明中定义一个或多个属性:background-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-size,和 background-attachment

对于所有简写属性,任何没有被指定的值都会被设定为它们的 初始值

语法

css
/* 使用 <background-color> */
background: green;

/* 使用 <bg-image> 和 <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 属性被指定多个背景层时,使用逗号分隔每个背景层。

每一层的语法如下:

备注: background-color 只能在 background 的最后一个属性上定义,因为整个元素只有一种背景颜色。

标准语法

background = 
<bg-layer>#? , <final-bg-layer>

<bg-layer> =
<bg-image> ||
<bg-position> [ / <bg-size> ]? ||
<repeat-style> ||
<attachment> ||
<visual-box> ||
<visual-box>

<final-bg-layer> =
<bg-image> ||
<bg-position> [ / <bg-size> ]? ||
<repeat-style> ||
<attachment> ||
<visual-box> ||
<visual-box> ||
<'background-color'>

<bg-image> =
<image> |
none

<bg-position> =
[ left | center | right | top | bottom | <length-percentage> ] |
[ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ] |
[ center | [ left | right ] <length-percentage>? ] && [ center | [ top | bottom ] <length-percentage>? ]

<bg-size> =
[ <length-percentage [0,∞]> | auto ]{1,2} |
cover |
contain

<repeat-style> =
repeat-x |
repeat-y |
[ repeat | space | round | no-repeat ]{1,2}

<attachment> =
scroll |
fixed |
local

<visual-box> =
content-box |
padding-box |
border-box

<image> =
<url> |
<gradient>

<length-percentage> =
<length> |
<percentage>

<url> =
<url()> |
<src()>

<url()> =
url( <string> <url-modifier>* ) |
<url-token>

<src()> =
src( <string> <url-modifier>* )

示例

HTML

html
<p class="topbanner">
  Starry sky<br />
  Twinkle twinkle<br />
  Starry sky
</p>
<p class="warning">Here is a paragraph</p>
<p></p>

CSS

css
.warning {
  background: red;
}

.topbanner {
  background: url("starsolid.gif") #99f repeat-y fixed;
}

结果

规范

Specification
CSS Backgrounds and Borders Module Level 3
# the-background

浏览器兼容性

BCD tables only load in the browser

参见