css背景图片制作
设置背景图片的基本方法
使用background-image属性指定图片路径,通常结合url()函数引入本地或网络资源:
.element {
background-image: url("path/to/image.jpg");
}
控制背景图片的重复方式
通过background-repeat调整图片平铺行为:
no-repeat:禁止重复,仅显示一次repeat-x:水平方向重复repeat-y:垂直方向重复.element { background-repeat: no-repeat; }
调整背景图片大小
使用background-size定义图片尺寸:
cover:缩放至完全覆盖容器(可能裁剪)contain:缩放至完整显示(可能留白)- 具体数值:如
100px 200px.element { background-size: cover; }
定位背景图片
通过background-position设置图片起始位置,支持关键词(top/center)或坐标:
.element {
background-position: center bottom; /* 水平居中,底部对齐 */
}
固定背景图片滚动
background-attachment控制图片是否随页面滚动:
scroll:默认跟随元素滚动fixed:固定相对于视口.element { background-attachment: fixed; }
复合写法简化代码
合并多个属性到background简写形式:
.element {
background: url("image.jpg") no-repeat center/cover fixed;
}
/* 顺序:image repeat position/size attachment */
响应式背景图片技巧
结合媒体查询适配不同屏幕尺寸:
.element {
background-image: url("small.jpg");
}
@media (min-width: 768px) {
.element {
background-image: url("large.jpg");
}
}
使用渐变作为背景
CSS渐变可替代图片生成动态背景:

.element {
background: linear-gradient(to right, #ff0000, #00ff00);
}
注意事项
- 图片路径建议使用相对路径或完整URL
- 高分辨率屏幕可准备
@2x尺寸图片 - 同时设置
background-color作为图片加载前的回退方案






