CSS背景
CSS背景属性详解
通过CSS背景属性可以为元素添加丰富的背景样式,包括颜色、图片、定位等效果,是前端开发中最常用的样式模块之一。
背景颜色
background-color: color|transparent|initial|inherit;- 默认值为
transparent(透明) - 支持所有合法的颜色表示方式(HEX、RGB、HSL、颜色名称等)
- 会填充元素的内容区域+内边距(padding)区域
<style>
.color-demo {
width: 200px;
height: 200px;
background-color: #ffc0cb; /* 十六进制表示 */
padding: 20px; /* 内边距也会被填充 */
}
</style>
<div class="color-demo"></div>提示
在CSS3中可以使用currentColor关键字继承当前元素的文字颜色作为背景色
背景图片
background-image: none|url("image.jpg")|linear-gradient()|...;适用场景:
- Logo展示(保持比例不变形)
- 装饰性元素(减少HTTP请求)
- 超大背景图(优化加载体验)
- CSS精灵图(性能优化)
<style>
.bg-image {
width: 800px;
height: 600px;
background-image: url("images/bg.jpg");
border: 1px solid #ccc; /* 添加边框便于观察 */
}
</style>警告
- 图片路径相对于CSS文件位置
- 建议同时设置背景颜色作为图片加载失败时的降级方案
- 现代浏览器支持多背景图(逗号分隔)
背景平铺
background-repeat: repeat|no-repeat|repeat-x|repeat-y|space|round;| 值 | 效果 | 使用场景 | |-||-| | repeat | 默认双向平铺 | 纹理背景 | | no-repeat | 不重复 | Logo/图标 | | repeat-x | 水平平铺 | 边框装饰 | | space | 等间距平铺 | 精确布局 | | round | 自适应平铺 | 响应式设计 |
.repeat-demo {
background-image: url("pattern.png");
background-repeat: round; /* 自适应平铺 */
}背景定位
background-position: x-axis y-axis;定位方式详解:
- 关键字定位(组合使用):
background-position: right bottom;- 精确单位(支持负值):
background-position: 20px -10px;- 百分比(基于容器和图片的差值):
background-position: 75% 25%;:::success CSS3新增四值语法:background-position: right 20px bottom 10px; :::
背景尺寸
background-size: length|percentage|cover|contain|auto;关键特性:
cover:完全覆盖(可能裁剪)contain:完整显示(可能留白)- 多背景图支持独立设置尺寸
.size-demo {
background: url("icon.png") no-repeat;
background-size: contain; /* 适合图标类元素 */
}背景固定
background-attachment: scroll|fixed|local;视差滚动实现原理:
<style>
.parallax {
background-image: url("bg.jpg");
background-attachment: fixed; /* 关键属性 */
background-position: center;
background-size: cover;
height: 100vh;
}
</style>警告
移动端对fixed支持有限,建议使用JavaScript polyfill
复合写法
background: [color] [image] [repeat] [attachment] [position]/[size];.header {
background: #fff url("logo.png") no-repeat fixed center/contain;
/* 等价于: */
background-color: #fff;
background-image: url("logo.png");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: contain;
}危险
简写时会覆盖所有背景属性,未指定的将重置为默认值
背景总结
| 属性 | 作用 | 值 | | | | | | background-color | 背景颜色 | 预定义的颜色值/十六进制/RGB | | background-image | 背景图片 | url(图片路径) | | background-repeat | 背景平铺 | repeat/no-repeat/repeat-x/repeat-y | | background-position | 背景位置 | length/position x/y | | background-attachment | 背景附着 | scroll(背景滚动)/fixed(背景固定) | | 背景简写 | 书写简单 | 背景颜色 背景图片地址 背景平铺 背景滚动 背景位置 | | 背景色半透明 | 背景色半透明 | background:rgba(0,0,0,0.3) |