理解 CSS background 属性的基本概念与作用
掌握 background 的各个子属性(颜色、图像、重复、定位、附着等)的使用方法
能够使用简写语法高效设置背景样式
了解现代网页中背景设计的最佳实践
CSS 的 background 是指元素内容区域背后的视觉层,它可以是:
单一颜色(如 lightblue)
图像(如 PNG、JPG、SVG)
颜色 + 图像的组合
渐变(线性或径向)
通过 background 相关属性,你可以精确控制背景的外观、位置、重复方式和滚动行为。
background 是一个复合简写属性,可以一次性设置多个背景相关样式:
element {
background: [color] [image] [repeat] [attachment] [position] [/ size];
}注意:顺序很重要!虽然某些值可省略,但推荐按标准顺序书写以避免解析错误。
示例
body {
background: lightblue
url("https://i1.hdslb.com/bfs/archive/e719365e2a47badea49bc793a95d899a71cac9ed.jpg")
no-repeat
center
fixed;
}这行代码等价于:
body {
background-color: lightblue;
background-image: url("https://i1.hdslb.com/bfs/archive/e719365e2a47badea49bc793a95d899a71cac9ed.jpg");
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
}background-color设置背景颜色。
取值方式:
颜色名称:red, blue, teal
HEX 值:#ff5733, #009900
RGB/RGBA:rgb(255, 0, 0), rgba(0, 0, 0, 0.5)
HSL/HSLA:hsl(120, 100%, 50%)
h1 {
background-color: #009900; /* GeeksforGeeks 绿色 */
}提示:即使使用背景图,也建议设置
background-color作为加载失败时的备用色。
background-image设置背景图像。支持多张图像(用逗号分隔)。
div {
background-image: url("pattern.png"), url("logo.svg");
}
默认行为:图像会重复平铺以填满整个元素
若未指定 background-color,背景默认为透明
background-repeat控制图像如何重复。
body {
background-image: url("stripe.png");
background-repeat: repeat-x; /* 创建横向条纹背景 */
}background-attachment定义背景图像是否随页面滚动。
.hero-section {
background-image: url("mountain.jpg");
background-attachment: fixed;
background-size: cover;
}
fixed常用于全屏英雄区域(Hero Section)实现沉浸式体验。
background-position设置背景图像的起始位置。
常用关键字:
水平:left, center, right
垂直:top, center, bottom
组合写法:
background-position: center top; /* 水平居中,顶部对齐 */
background-position: 20px 50px; /* 距左 20px,距顶 50px */
background-position: 50% 50%; /* 百分比定位(等同于 center center) */技巧:
center是最常用的值,尤其配合no-repeat实现居中图标或 logo。
background-size控制背景图像的尺寸。
auto(默认):保持原始尺寸
cover:缩放图像以完全覆盖元素(可能裁剪)
contain:缩放图像以完整显示在元素内(可能留空)
具体值:100px 200px, 50% auto
body {
background-size: cover; /* 常用于全屏背景图 */
}background-origin定义 background-position 的参考区域:
padding-box(默认)
border-box
content-box
background-clip定义背景绘制区域:
border-box(默认)
padding-box
content-box
text(配合 -webkit-background-clip: text 可实现文字渐变)
CSS 支持多层背景,从上到下叠加:
.multi-bg {
background:
url("icon.png") no-repeat top right,
url("pattern.jpg") repeat,
linear-gradient(to bottom, #fff, #eee);
}第一个图像在最上层,最后一个在最底层。
始终提供 fallback 色
background: #f0f0f0 url("bg.jpg") no-repeat center;优化图片性能
使用 WebP 格式
控制文件大小
对装饰性图像使用 alt="" 或 CSS 而非 <img>
响应式背景
@media (max-width: 768px) {
.hero {
background-image: url("mobile-bg.jpg");
}
}避免过度使用 fixed
在移动设备上,background-attachment: fixed 可能导致性能问题或不支持。
如果同时设置了 background-color 和 background-image,哪个会显示在上层?
为什么在移动端应谨慎使用 background-attachment: fixed?
如何实现一个“背景图只在内容区域显示,不延伸到 padding 区域”的效果?
使用 background-size: cover 和 contain 时,图像可能会变形吗?为什么?