CSS background
属性用于为元素的背景添加颜色或图像。例如,
h1 {
background: orange;
}
浏览器输出

这里,background
属性为 h1
元素添加了 orange
颜色作为背景。
CSS 背景作为简写属性
有多种 CSS 背景属性可以组合到单个 background
属性中作为简写。background
简写属性的语法是:
background: background-image background-position / background-size background-repeat background-attachment background-origin background-clip background-color;
这里,
- background-image:允许为元素的背景添加图像
- background-position:指定元素内背景图像的位置
- background-size:指定背景图像的大小
- background-repeat:控制背景图像的重复行为
- background-attachment:控制背景图像是随页面内容滚动还是固定
- background-origin:指定元素内背景区域的起始位置
- background-clip:定义元素的背景裁剪区域
- background-color:设置元素的背景颜色
注意:简写 background
属性值的顺序推荐按照语法进行。如果省略了任何值,则将采用该属性值的默认值。
示例:CSS 背景简写属性
让我们看一个例子,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background</title>
</head>
<body>
<!-- Adding a background image -->
</body>
</html>
body {
/* background shorthand property */
background: url("avatar.png") top center no-repeat lightgray;
}
浏览器输出

在上面的例子中:
background: url("avatar.png") top center no-repeat lightgray;
等同于:
body {
background-image: url("avatar.png");
background-position: top center;
background-repeat: no-repeat;
background-color: lightgray;
}