# CSS3教程 - 11 背景

下面来讲解一下背景相关的样式。主要是背景颜色和背景图片的设置。


# 11.1 background-color

background-color 属性用于设置元素的背景颜色,之前在讲解的时候,很多地方都用到了。

举个栗子:

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        background-color: red;  /* 设置背景颜色 */
        width: 100px;
        height: 100px;
      }
    </style>
  </head>

  <body>
    <div></div>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  • 上面为 div 设置了背景颜色为红色,也可以使用 #FF0000

背景颜色没什么好说的,过!

# 11.2 background-image

background-image 用来设置背景图片。

举个栗子:

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        background-image: url('./image/foooor.png');  /* 设置背景图片 */
        width: 250px;
        height: 66px;
        border: 1px solid red;
      }
    </style>
  </head>

  <body>
    <div></div>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  • 上面通过 background-image 属性设置背景图片,图片路径通过 url() 来指定;
  • 注意:上面元素的尺寸和图片的尺寸是一致的。

显示如下:

显示没有问题,但是这里涉及到三种情况:

  • 如果背景图片尺寸等于元素尺寸,背景图片会直接正常显示,就像上面的;
  • 如果背景图片尺寸小于元素尺寸,背景图片会在元素重复显示;
  • 如果背景图片尺寸大于元素尺寸,背景图片一部分会无法完全显示;

如下图:

背景颜色和背景图片是可以同时设置的。

举个栗子:

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        background-color: lightblue;
        background-image: url('./image/foooor.png');  /* 设置背景图片 */
        width: 260px;
        height: 80px;
        border: 1px solid red;
      }
    </style>
  </head>

  <body>
    <div></div>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  • 上面同时设置了背景颜色和图片,需要注意,图片空白的地方是透明的。

# 11.3 background-repeat

上面在背景图片小于元素尺寸的时候,图片会重复平铺,通过 background-repeat 属性可以设置背景图片的重复方式。

可选值如下:

  • repeat 默认值,背景图片沿着 x 轴和 y 轴方向重复;
  • repeat-x 背景图片沿着 x 轴方向重复;
  • repeat-y 背景图片沿着 y 轴方向重复;
  • no-repeat 背景图片不重复。

内容未完......