如何在 CSS 中设置元素的背景图片?

在 CSS 中,可以通过以下几种方式设置元素的背景图片:

一、使用`background-image`属性

1. 基本用法:

.element-with-bg-image {
     background-image: url('image.jpg');
   }

   这里将名为`image.jpg`的图片设置为具有类名`.element-with-bg-image`的元素的背景图片。

2. 多个背景图片:

   可以使用逗号分隔多个`url()`来设置多个背景图片。

.multiple-bg-images {
     background-image: url('image1.jpg'), url('image2.jpg');
   }

二、控制背景图片的重复方式(`background-repeat`)

1. 不重复:

.no-repeat-bg {
     background-image: url('image.jpg');
     background-repeat: no-repeat;
   }

2. 水平重复:

.repeat-x-bg {
     background-image: url('image.jpg');
     background-repeat: repeat-x;
   }

3. 垂直重复:

.repeat-y-bg {
     background-image: url('image.jpg');
     background-repeat: repeat-y;
   }

三、设置背景图片的位置(`background-position`)

1. 使用关键字: 

.centered-bg {
     background-image: url('image.jpg');
     background-repeat: no-repeat;
     background-position: center;
   }

   这里将背景图片居中显示。其他关键字还包括`top`、`bottom`、`left`、`right`等,可以组合使用,如`top left`表示左上角。

2. 使用具体数值或百分比:

.specific-position-bg {
     background-image: url('image.jpg');
     background-repeat: no-repeat;
     background-position: 50px 100px;
   }

   这里将背景图片定位在距离元素左边 50 像素,距离元素顶部 100 像素的位置。也可以使用百分比,如`50% 50%`表示将背景图片居中显示在元素中。

四、固定背景图片(`background-attachment`)

1. 固定:

.fixed-bg {
     background-image: url('image.jpg');
     background-repeat: no-repeat;
     background-position: center;
     background-attachment: fixed;
   }

   背景图片将固定在浏览器窗口中,不会随着页面滚动而移动。

2. 滚动(默认值):

.scroll-bg {
     background-image: url('image.jpg');
     background-repeat: no-repeat;
     background-position: center;
     background-attachment: scroll;
   }

   背景图片会随着页面滚动而移动。

五、简写方式(`background`)

可以将多个背景属性合并在一个`background`属性中书写,顺序通常为`background-color`、`background-image`、`background-repeat`、`background-attachment`、`background-position`。

.combined-bg {
  background: #00ff00 url('image.jpg') no-repeat fixed center;
}

这里同时设置了背景颜色为绿色,背景图片为`image.jpg`,不重复,固定在窗口中,并居中显示。