目录

CSS 背景简写


CSS 背景 - 简写属性

为了缩短代码,还可以在一个属性中指定所有背景属性。这称为简写属性。

而不是写:

body {
  background-color: #ffffff;
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
}

您可以使用简写属性background

示例

使用简写属性在一个声明中设置背景属性:

body {
  background: #ffffff url("img_tree.png") no-repeat right top;
}
亲自试一试 »

使用简写属性时,属性值的顺序为:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

只要其他属性值按此顺序排列,即使缺少其中一个属性值也没关系。请注意,我们在上面的示例中没有使用 background-attachment 属性,因为它没有值。


通过练习测试一下

练习:

将 <h1> 元素的背景颜色设置为"lightblue"。

<style>
h1 {
  : lightblue;
}
</style>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
  <p>This is a paragraph</p>
</body>

开始练习


所有 CSS 背景属性

Property Description
background Sets all the background properties in one declaration
background-attachment Sets whether a background image is fixed or scrolls with the rest of the page
background-clip Specifies the painting area of the background
background-color Sets the background color of an element
background-image Sets the background image for an element
background-origin Specifies where the background image(s) is/are positioned
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated
background-size Specifies the size of the background image(s)