background

介绍

background是一种 CSS 简写属性,用于一次性集中定义各种背景属性,包括 color,image,origin 与 size,repeat 方式等等。 这是一个简写属性,可以在一次声明中定义一个或多个属性:background-clip,background-color,background-image,background-origin,background-position,background-repeat,background-size

取值

/* 使用 <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');
1
2
3
4
5
6
7
8
9
10
11

background属性被指定多个背景层时,使用逗号分隔每个背景层。
每一次的语法如下:

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

<box>

参见background-clipbackground-origin

<background-color>

参见background-color

<bg-image>

参见background-image

<position>

参见background-position

<repeat-style>

参见background-repeat

<bg-size>

参见background-size

标准化语法

[ <bg-layer> , ]* <final-bg-layer>

where

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

where

<bg-image> = none | <image>
<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> | auto ]{1,2} | cover | contain
<repeat-style> = repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1, 2}
<box> = border-box | padding-box | content-box

where

<image> = <url> | <gradient>
<length-percentage> = <length> | <percentage>

where

<gradient> = <linear-gradient> | <radial-gradient>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

与 Web 的区别

  • <bg-layer> 中不支持<attachment>open in new window属性。
  • <image> 中只支持<url><gradient>

    标准 web 中还支持 <image-set><element()><paint()><cross-fade()>等自定义绘图属性。

  • <gradient> 中目前只支持<linear-gradient><radial-gradient>

    标准 web 中还支持<repeating-linear-gradient()>,<radial-gradient()>,<repeating-radial-gradient()>,<conic-gradient()>

注意事项

  • color 必须写在最后一个 image 中,否则 parser 会认为这是一个无效 background
    例如: background: red url('./a.png'), url('./b.png);'会被当作错误的写法直接忽略。
    正确的写法应该是:background: url('./a.png'),red url('./b.png);
Last Updated: 2022/7/15 下午7:22:06