Appearance
CSS Backgrounds(背景)
通过 CSS 可以给元素设置背景颜色或背景图片,并控制其铺排方式、位置和大小。这些属性统称为「背景」相关属性。
常用背景属性一览
| 属性 | 作用简述 |
|---|---|
background-color | 背景颜色 |
background-image | 背景图片 |
background-repeat | 背景是否重复、如何重复 |
background-position | 背景图在元素中的位置 |
background-size | 背景图尺寸 |
background-attachment | 背景是否随滚动(固定/滚动) |
background | 简写,可一次写多个背景属性 |
1. background-color(背景颜色)
为元素设置纯色背景。
css
body {
background-color: #f0f0f0;
}
.box {
background-color: rgb(255, 200, 100);
}
.header {
background-color: blue;
}取值方式:
- 颜色名:
red、blue、transparent(透明) - 十六进制:
#fff、#ffffff、#ff6600 rgb(r, g, b):如rgb(255, 0, 0)rgba(r, g, b, a):带透明度,如rgba(0,0,0,0.5)
2. background-image(背景图片)
用图片作为背景。
css
.banner {
background-image: url("images/bg.jpg");
}url("路径"):图片路径可以是相对路径或绝对路径。- 若同时设置了
background-color,图片会盖在颜色上面;图片有透明区域时,会露出背景色。
3. background-repeat(重复方式)
控制背景图是否重复以及如何重复。默认是平铺(repeat)。
css
.banner {
background-image: url("bg.jpg");
background-repeat: no-repeat; /* 不重复,只显示一张 */
}
.tile {
background-repeat: repeat; /* 默认:横向、纵向都重复 */
}
.strip-h {
background-repeat: repeat-x; /* 只横向重复 */
}
.strip-v {
background-repeat: repeat-y; /* 只纵向重复 */
}常用值:repeat、no-repeat、repeat-x、repeat-y。
4. background-position(背景位置)
指定背景图在元素内的位置。适合在 background-repeat: no-repeat 时使用。
css
.hero {
background-image: url("hero.jpg");
background-repeat: no-repeat;
background-position: center center; /* 水平居中、垂直居中 */
}
.logo-bg {
background-position: left top; /* 左上 */
}
.footer-bg {
background-position: right bottom; /* 右下 */
}取值:
- 关键字:
left/center/right与top/center/bottom,可组合使用。 - 数值:
50% 50%、10px 20px(先水平后垂直)。
5. background-size(背景图尺寸)
控制背景图的宽高。
css
.cover {
background-size: cover; /* 铺满元素,可能裁剪 */
}
.contain {
background-size: contain; /* 完整显示在元素内,可能留白 */
}
.custom {
background-size: 200px 100px; /* 宽 200px,高 100px */
}
.percent {
background-size: 50% 80%; /* 相对元素宽高的比例 */
}cover:按比例放大填满元素,多出的部分被裁掉。contain:按比例缩放,保证整张图都在元素内,可能留白。
6. background-attachment(固定或滚动)
背景是随内容滚动,还是固定在视口(如「视差」效果)。
css
.parallax {
background-image: url("bg.jpg");
background-attachment: fixed; /* 相对视口固定,滚动时背景不动 */
}
.normal {
background-attachment: scroll; /* 默认:随元素一起滚动 */
}7. background 简写
把多个背景属性写在一行,可读性会差一些,但写起来快。
css
.box {
background: #eee url("bg.png") no-repeat center center / cover;
}常见顺序:color image repeat position / size,其中 position 和 size 用 / 隔开(若写 size)。未写的属性会使用默认值。
建议
新手可先分别写 background-color、background-image、background-repeat 等,熟悉后再用 background 简写。
多背景(同一元素多张图)
同一个元素可以设置多张背景图,用逗号分隔;先写的在上层。
css
.multi {
background-image: url("overlay.png"), url("base.jpg");
background-repeat: no-repeat, no-repeat;
background-position: center, center;
}小结
- 背景颜色:
background-color;背景图:background-image: url(...)。 - 不重复:
background-repeat: no-repeat;位置:background-position;大小:background-size(如cover/contain)。 - 固定背景:
background-attachment: fixed。 - 简写:
background可一次写多个属性;多张图用逗号分隔。
下一节我们学习 CSS Text(文本):文字颜色、对齐、行高、缩进等。