css背景图片制作
使用CSS设置背景图片
在CSS中,可以通过background-image属性为元素添加背景图片。以下是一个基本示例:
.element {
background-image: url('path/to/image.jpg');
}
控制背景图片的显示方式
background-repeat属性控制图片是否重复显示:
.element {
background-repeat: no-repeat; /* 不重复 */
background-repeat: repeat-x; /* 水平重复 */
background-repeat: repeat-y; /* 垂直重复 */
}
调整背景图片大小
使用background-size属性可以调整背景图片尺寸:
.element {
background-size: cover; /* 覆盖整个元素 */
background-size: contain; /* 保持比例完整显示 */
background-size: 50% auto; /* 自定义尺寸 */
}
定位背景图片
background-position属性控制图片在元素中的位置:

.element {
background-position: center center; /* 居中 */
background-position: 20px 30px; /* 自定义位置 */
background-position: right bottom; /* 右下角 */
}
多背景图片设置
CSS3支持为一个元素设置多个背景图片:
.element {
background-image: url('image1.png'), url('image2.jpg');
background-position: left top, right bottom;
background-repeat: no-repeat, repeat-x;
}
背景图片固定或滚动
background-attachment属性控制背景图片是否随内容滚动:

.element {
background-attachment: fixed; /* 固定 */
background-attachment: scroll; /* 滚动 */
background-attachment: local; /* 随元素内容滚动 */
}
背景简写属性
可以使用background简写属性一次性设置多个背景属性:
.element {
background: url('image.jpg') no-repeat center center/cover fixed;
}
响应式背景图片
结合媒体查询可以创建响应式背景:
.element {
background-image: url('small.jpg');
}
@media (min-width: 768px) {
.element {
background-image: url('large.jpg');
}
}
使用渐变作为背景
除了图片,CSS还支持使用渐变作为背景:
.element {
background: linear-gradient(to right, #ff0000, #0000ff);
}






