background 属性
background 属性是 CSS 中的一个强大简写属性, 它整合了多个子属性来定义元素的背景, 包括:
background-image:设置背景图像.background-size:调整背景图像的大小.background-repeat:控制背景图像的重复方式.background-position:指定背景图像的位置.background-origin:定义背景的定位起点.background-clip:确定背景的绘制区域.background-attachment:控制背景的滚动行为.background-color:设置背景颜色.
简写语法
background 的简写形式因其高效而被广泛使用. 例如:
1.box {2background: url('image.jpg') no-repeat center / cover fixed #fff;3}
这行代码同时设置了 background-image、background-repeat、background-position、background-size、background-attachment 和 background-color. 值的顺序有一定要求, 但如果某些属性使用默认值, 可以省略(参考 W3C CSS 背景模块第 3 级).
background-image 属性
background-image 属性通过 URL 指定一个或多个背景图像. 多个图像用逗号分隔, 按从上到下的层级顺序排列.
linear-gradient 是 CSS 中的一个函数, 用于创建线性渐变背景.
1.box {2background-image: url('texture.png'), linear-gradient(to right, red, blue);3}
background-size 属性
background-size 属性用于调整背景图像的大小. 常用值包括:
cover:按比例缩放图像以覆盖整个元素, 必要时裁剪多余部分.contain:按比例缩放图像以完全适应元素内部, 不裁剪.auto:保持图像的原始大小.- 长度或百分比:如
100px 100px或50% 50%.
1.box {2background-size: contain;3}
background-repeat 属性
background-repeat 属性控制背景图像的重复方式:
repeat:水平和垂直方向都重复.repeat-x:仅水平方向重复.repeat-y:仅垂直方向重复.no-repeat:不重复.
1.box {2background-repeat: no-repeat;3}
background-position 属性
background-position 属性用于定位背景图像, 支持以下方式:
- 关键字:
left、center、right、top、bottom. - 百分比:如
50% 50%(居中). - 长度:如
20px 30px.
1.box {2background-position: top right;3}
background-origin 属性
background-origin 属性定义背景定位的起点:
padding-box:从内边距边缘开始(默认).border-box:从边框边缘开始.content-box:从内容边缘开始.
1.box {2background-origin: content-box;3}
background-clip 属性
background-clip 属性指定背景的绘制区域:
padding-box:裁剪到内边距边缘.border-box:裁剪到边框边缘(默认).content-box:裁剪到内容边缘.
1.box {2background-clip: content-box;3}
与 background-origin 结合使用
将 background-origin: border-box 与 background-clip: content-box 搭配使用, 可以创建一个从边框开始但在内容处裁剪的背景, 适合带边框的设计效果.
background-attachment 属性
background-attachment 属性决定背景的滚动行为:
scroll:随页面内容滚动(默认).fixed:相对于视口固定.local:随元素内部内容滚动(例如在可滚动 div 内).
1.box {2background-attachment: local;3}
使用 fixed 将背景图像固定在视口上.
使用 local 使背景图像随容器和视口一起滚动.
使用 scroll 使背景图像随容器滚动.
background-color 属性
background-color 属性设置背景颜色, 支持以下格式:
- 关键字:
red、transparent. - 十六进制:
#FF5733. - RGB/RGBA:
rgb(255, 87, 51)、rgba(255, 87, 51, 0.5). - HSL/HSLA:
hsl(12, 100%, 60%).
1.box {2background-color: rgba(0, 128, 255, 0.8);3}