创建时间: 2026-03-24最后更新: 2026-04-19

background 属性

background 属性是 CSS 中的一个强大简写属性, 它整合了多个子属性来定义元素的背景, 包括:

  • background-image:设置背景图像.
  • background-size:调整背景图像的大小.
  • background-repeat:控制背景图像的重复方式.
  • background-position:指定背景图像的位置.
  • background-origin:定义背景的定位起点.
  • background-clip:确定背景的绘制区域.
  • background-attachment:控制背景的滚动行为.
  • background-color:设置背景颜色.

简写语法

background 的简写形式因其高效而被广泛使用. 例如:

index.css
1
.box {
2
background: url('image.jpg') no-repeat center / cover fixed #fff;
3
}

这行代码同时设置了 background-imagebackground-repeatbackground-positionbackground-sizebackground-attachmentbackground-color. 值的顺序有一定要求, 但如果某些属性使用默认值, 可以省略(参考 W3C CSS 背景模块第 3 级).

background-image 属性

background-image 属性通过 URL 指定一个或多个背景图像. 多个图像用逗号分隔, 按从上到下的层级顺序排列.

linear-gradient 是 CSS 中的一个函数, 用于创建线性渐变背景.

index.css
1
.box {
2
background-image: url('texture.png'), linear-gradient(to right, red, blue);
3
}
预览
预览
预览

background-size 属性

background-size 属性用于调整背景图像的大小. 常用值包括:

  • cover:按比例缩放图像以覆盖整个元素, 必要时裁剪多余部分.
  • contain:按比例缩放图像以完全适应元素内部, 不裁剪.
  • auto:保持图像的原始大小.
  • 长度或百分比:如 100px 100px50% 50%.
index.css
1
.box {
2
background-size: contain;
3
}
预览
预览
预览

background-repeat 属性

background-repeat 属性控制背景图像的重复方式:

  • repeat:水平和垂直方向都重复.
  • repeat-x:仅水平方向重复.
  • repeat-y:仅垂直方向重复.
  • no-repeat:不重复.
index.css
1
.box {
2
background-repeat: no-repeat;
3
}
预览

background-position 属性

background-position 属性用于定位背景图像, 支持以下方式:

  • 关键字:leftcenterrighttopbottom.
  • 百分比:如 50% 50%(居中).
  • 长度:如 20px 30px.
index.css
1
.box {
2
background-position: top right;
3
}
预览

background-origin 属性

background-origin 属性定义背景定位的起点:

  • padding-box:从内边距边缘开始(默认).
  • border-box:从边框边缘开始.
  • content-box:从内容边缘开始.
index.css
1
.box {
2
background-origin: content-box;
3
}
预览

background-clip 属性

background-clip 属性指定背景的绘制区域:

  • padding-box:裁剪到内边距边缘.
  • border-box:裁剪到边框边缘(默认).
  • content-box:裁剪到内容边缘.
index.css
1
.box {
2
background-clip: content-box;
3
}
预览
预览

background-origin 结合使用

background-origin: border-boxbackground-clip: content-box 搭配使用, 可以创建一个从边框开始但在内容处裁剪的背景, 适合带边框的设计效果.

background-attachment 属性

background-attachment 属性决定背景的滚动行为:

  • scroll:随页面内容滚动(默认).
  • fixed:相对于视口固定.
  • local:随元素内部内容滚动(例如在可滚动 div 内).
index.css
1
.box {
2
background-attachment: local;
3
}

使用 fixed 将背景图像固定在视口上.

预览

使用 local 使背景图像随容器和视口一起滚动.

预览

使用 scroll 使背景图像随容器滚动.

预览

background-color 属性

background-color 属性设置背景颜色, 支持以下格式:

  • 关键字:redtransparent.
  • 十六进制:#FF5733.
  • RGB/RGBA:rgb(255, 87, 51)rgba(255, 87, 51, 0.5).
  • HSL/HSLA:hsl(12, 100%, 60%).
index.css
1
.box {
2
background-color: rgba(0, 128, 255, 0.8);
3
}
预览