CSS 背景简写
学习 background 简写属性 · 难度:进阶 · +15XP
CSS 背景简写属性
CSS 提供了 background 简写属性,可以在一条声明中设置所有背景相关属性,大幅减少代码量。理解简写属性的规则对于高效编写 CSS 至关重要。
background 简写语法
background: [color] [image] [position] / [size] [repeat] [attachment] [origin] [clip];
虽然看起来复杂,但日常使用中通常只需要几个关键值。以下是最常用的组合:
/* 纯色背景 */
background: #f0f0f0;
/* 背景图片 + 不重复 + 居中 */
background: url('bg.jpg') no-repeat center;
/* 背景图片 + 覆盖 + 固定 */
background: url('hero.jpg') center / cover no-repeat fixed;
背景相关子属性
| 属性 | 说明 | 常用值 |
|---|---|---|
background-color | 背景颜色 | #fff, transparent |
background-image | 背景图片 | url(), linear-gradient() |
background-position | 背景图像起始位置 | center, top left, 50% 50% |
background-size | 背景图像尺寸 | cover, contain, 100% auto |
background-repeat | 背景是否重复 | no-repeat, repeat-x, repeat-y |
background-attachment | 背景是否随滚动 | scroll, fixed, local |
background-origin | 背景绘制区域 | padding-box, border-box, content-box |
background-clip | 背景裁剪区域 | border-box, padding-box, text |
background-size 详解
/* cover — 覆盖整个容器,可能裁剪 */
background-size: cover;
/* contain — 完整显示图片,可能留白 */
background-size: contain;
/* 固定尺寸 */
background-size: 200px 150px;
/* 百分比 — 相对于背景定位区域 */
background-size: 100% 100%;
多重背景
CSS3 支持在一个元素上设置多个背景,用逗号分隔:
background:
url('overlay.png') center / cover no-repeat,
linear-gradient(135deg, #667eea 0%, #764ba2 100%),
url('pattern.png') repeat;
层叠顺序:最先声明的背景在最上层。
渐变背景
渐变是通过 background-image 设置的,但通常在简写中使用:
/* 线性渐变 */
background: linear-gradient(90deg, red, blue);
/* 径向渐变 */
background: radial-gradient(circle, yellow, green);
/* 锥形渐变 */
background: conic-gradient(red, yellow, green, blue, red);
/* 重复渐变 — 条纹效果 */
background: repeating-linear-gradient(
45deg,
#606dbc,
#606dbc 10px,
#465298 10px,
#465298 20px
);
简写注意事项
- 未在简写中指定的子属性会自动重置为默认值
background-size必须写在background-position之后,并用/分隔- 如果简写中不包含
background-color,它会被重置为transparent - 建议将简写属性放在前面,需要覆盖的子属性单独声明
实用示例
.hero {
background: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
url('hero.jpg') center / cover no-repeat fixed;
color: white;
min-height: 80vh;
display: flex;
align-items: center;
justify-content: center;
}
熟练使用 background 简写属性能让你的 CSS 更简洁高效。记住位置 / 尺寸的语法格式,这是最容易出错的地方。