CSS 背景
学习 background-color/image/repeat/position/size · 难度:入门 · +10XP
CSS 背景属性详解
CSS 背景属性可以让你为 HTML 元素设置颜色、图像和渐变作为背景。精心设计的背景能大幅提升网页的视觉吸引力。背景属性有多种简写和单独设置的方式,掌握它们对于日常开发非常重要。
背景颜色 background-color
background-color 设置元素的背景色。可以是任何 CSS 颜色值。
body {
background-color: #f5f5f5;
}
.highlight {
background-color: yellow;
}
.overlay {
background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
}
背景图像 background-image
background-image 设置元素的背景图片。可以设置一张或多张图片(用逗号分隔),还可以使用渐变。
/* 单张图片 */
.hero {
background-image: url('/images/bg.jpg');
}
/* 多张图片叠加 */
.overlay-bg {
background-image:
linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
url('/images/hero.jpg');
}
/* 使用渐变作为背景 */
.gradient-bg {
background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
背景重复 background-repeat
控制背景图像的平铺方式。
div {
background-repeat: no-repeat; /* 不平铺 */
background-repeat: repeat-x; /* 仅水平平铺 */
background-repeat: repeat-y; /* 仅垂直平铺 */
background-repeat: repeat; /* 默认,双向平铺 */
background-repeat: space; /* 均匀分布不裁剪 */
background-repeat: round; /* 缩放以填满 */
}
背景定位 background-position
控制背景图像在元素中的起始位置。
div {
background-position: center; /* 居中 */
background-position: top right; /* 右上角 */
background-position: 50% 50%; /* 百分比 */
background-position: 10px 20px; /* 像素偏移 */
background-position: left bottom; /* 左下角 */
}
背景尺寸 background-size
div {
background-size: cover; /* 覆盖整个容器(可能裁剪) */
background-size: contain; /* 完整显示(可能有留白) */
background-size: 100% 100%; /* 拉伸填充 */
background-size: 200px 150px; /* 固定尺寸 */
}
背景附着 background-attachment
background-attachment 决定背景图像是否跟随滚动。
/* 视差滚动效果 */
.parallax {
background-image: url('bg.jpg');
background-attachment: fixed; /* 背景固定不滚动 */
background-size: cover;
}
.normal {
background-attachment: scroll; /* 默认,随内容滚动 */
}
.local-scroll {
background-attachment: local; /* 随元素内滚动 */
}
背景简写 background
background 是一个强大的简写属性,可以在一条声明中设置所有背景属性。
/* 完整简写 */
.hero {
background: #333 url('bg.jpg') no-repeat center/cover fixed;
}
/* 简洁用法 */
body {
background: #f0f0f0;
}
.card {
background: white;
border-radius: 8px;
}
背景属性速查表
| 属性 | 作用 | 常用值 |
|---|---|---|
| background-color | 背景颜色 | 颜色值 / transparent |
| background-image | 背景图像 | url() / linear-gradient() |
| background-repeat | 背景重复 | no-repeat / repeat-x / repeat-y |
| background-position | 背景定位 | center / top right / 50% 50% |
| background-size | 背景尺寸 | cover / contain / 100% auto |
| background-attachment | 背景附着 | scroll / fixed / local |
| background-clip | 背景裁剪区域 | border-box / padding-box / content-box |
| background-origin | 背景定位原点 | padding-box / border-box / content-box |
???? 练习
- 为页面设置一个浅灰色背景,hero 区域使用背景图片 + cover
- 使用半透明渐变叠加在背景图片上创建暗色遮罩效果
- 实现一个 background-attachment: fixed 的视差滚动效果
- 分别尝试 cover 和 contain 的区别,理解裁剪与完整显示
- 使用 background 简写属性一次性设置多个背景属性