1. 《CSS背景属性:图像渲染与布局控制详解》
1.1 背景属性作用
- 1.1.1 核心作用
👉 控制元素的背景颜色、背景图片及其展示方式 - 1.1.2 应用场景
- 页面背景
- 卡片背景
- Banner图
- 按钮背景
1.2 背景颜色(background-color)
- 1.2.1 写法
div {
background-color: pink;
}
- 1.2.2 特点
- 设置元素背景色
- 默认是透明
1.3 背景图片(background-image)
- 1.3.1 写法
div {
background-image: url(‘img.png’);
}
- 1.3.2 注意
- 路径必须正确
- 图片默认会平铺
1.4 背景平铺(background-repeat)
- 1.4.1 常用值
background-repeat: repeat; /* 默认,平铺 /
background-repeat: no-repeat; / 不平铺 */
1.5 背景位置(background-position)
- 1.5.1 写法
background-position: left top;
background-position: center center;
background-position: right bottom;
- 1.5.2 规则
- 第一个值:水平方向
- 第二个值:垂直方向
1.6 背景大小(background-size)
- 1.6.1 常用值
background-size: cover; /* 填满容器(可能裁剪) /
background-size: contain; / 完整显示(可能留空) */
background-size: 100% 100%;
- 1.6.2 核心理解
- cover:铺满优先
- contain:完整优先
1.7 背景滚动(background-attachment)
- 1.7.1 写法
background-attachment: scroll; /* 默认 /
background-attachment: fixed; / 固定背景 */
- 1.7.2 作用
👉 控制背景是否随页面滚动
1.8 连写(重点)
1.8.1 标准写法
div {
background: url(‘img.png’) no-repeat center/cover;
}
1.8.2 组成结构
- 图片(url)
- 平铺(repeat)
- 位置(position)
- 大小(size)
1.8.3 特别注意
position / size用/分隔- 顺序不严格要求(和font不同)
2. 综合示例(实战)
body {
background: url(‘bg.png’) no-repeat center/cover;
}
👉 效果:
- 图片居中
- 不平铺
- 填满屏幕
3. 本章核心总结(必须掌握)
3.1 五大核心属性
- background-color
- background-image
- background-repeat
- background-position
- background-size
3.2 最常用一行代码
background: url(‘img.png’) no-repeat center/cover;
👉 80%场景直接用这个
3.3 高频考点
- cover vs contain
- position 写法
- 连写规则
3.4 实战理解(关键)
- 做全屏背景 → cover
- 做完整展示 → contain
- 做图标 → no-repeat + position
3.5 一句话总结
👉 background = 控制“背景如何显示”的一整套机制