提示

本文主要讲解 CSS 多重背景的使用。@ermo

# CSS3 背景

# 多重背景(background)

CSS3 中 background 属性可以书写多重背景,使用英文逗号 , 隔开。最先书写的背景图位于屏幕的最上层。

示例:

<div class="bg"></div>
.bg {
    width: 400px;
    height: 200px;
    background: url(../../static/image/flower.gif), url(../../static/image/paper.gif);
    background-position: right bottom, left top;
    background-repeat: no-repeat, repeat;
}

background 同样支持简写形式:

.bg1 {
    width: 400px;
    height: 200px;
    background: url(../../static/image/flower.gif) right bottom no-repeat, url(../../static/image/paper.gif) left top repeat;
}

# 背景尺寸(background-size)

background-size 属性可以修改背景图片的尺寸。

属性值的书写有三种方式:

  • 像素,例如 20px
  • 百分比,比如 50%
  • 关键字,有 containcover 以及 auto

使用像素的形式书写时,一个值表示背景图片的宽和高都是这个值;

两个值的时候分别表示背景图片的宽度和高度。

<div class="bg2"></div>
.bg2 {
    width: 200px;
    height: 200px;
    background: url(../../static/image/flower.gif);
    background-size: 50px 20px;
}

使用百分比形式书写时,一个值表示背景图片的宽高都是相对于父元素宽高的百分比;

两个值的时候表示,每个值相对于父元素的宽高百分比。

<div class="bg3"></div>
.bg3 {
    width: 200px;
    height: 200px;
    background: url(../../static/image/flower.gif);
    background-size: 100%;
}