CSS3 背景

CSS3 中包含几个新的背景属性,提供更大背景元素控制。
在本章您将了解以下背景属性:
  • background-image
  • background-size
  • background-origin
  • background-clip

您还将学习如何使用多重背景图像。


浏览器支持

表格中的数字表示支持该属性的第一个浏览器版本号。
紧跟在 -webkit-, -ms- 或 -moz- 前的数字为支持该前缀属性的第一个浏览器版本号。
属性
background-image
(with multiple backgrounds)
4.0 9.0 3.6 3.1 11.5
background-size 4.0
1.0 -webkit-
9.0 4.0
3.6 -moz-
4.1
3.0 -webkit-
10.5
10.0 -o-
background-origin 1.0 9.0 4.0 3.0 10.5
background-clip 4.0 9.0 4.0 3.0 10.5

CSS3 background-image属性
CSS3中可以通过background-image属性添加背景图片。
不同的背景图像和图像用逗号隔开,所有的图片中显示在最顶端的为第一张。
#example1 { 
    background-image: url(img_flwr.gif), url(paper.gif); 
    background-position: right bottom, left top; 
    background-repeat: no-repeat, repeat; 
}
可以给不同的图片设置多个不同的属性
#example1 {
    background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
}

CSS3 background-size 属性
background-size指定背景图像的大小。CSS3以前,背景图像大小由图像的实际大小决定。
CSS3中可以指定背景图片,让我们重新在不同的环境中指定背景图片的大小。您可以指定像素或百分比大小。
你指定的大小是相对于父元素的宽度和高度的百分比的大小。
重置背景图像:
div
{
    background:url(img_flwr.gif);
    background-size:80px 60px;
    background-repeat:no-repeat;
}
伸展背景图像完全填充内容区域:
div
{
    background:url(img_flwr.gif);
    background-size:100% 100%;
    background-repeat:no-repeat;
}

CSS3 的 background-origin 属性
background-origin 属性指定了背景图像的位置区域。
content-box, padding-box,和 border-box区域内可以放置背景图像。

在 content-box 中定位背景图片:
div
{
    background:url(img_flwr.gif);
    background-repeat:no-repeat;
    background-size:100% 100%;
    background-origin:content-box;
}

CSS3 多个背景图像
CSS3 允许你在元素上添加多个背景图像。
在 body 元素中设置两个背景图像:
body
{ 
    background-image:url(img_flwr.gif),url(img_tree.gif);
}

CSS3 background-clip属性
CSS3中background-clip背景剪裁属性是从指定位置开始绘制。
#example1 { 
    border: 10px dotted black; 
    padding: 35px; 
    background: yellow; 
    background-clip: content-box; 
}

CSS3 多重背景(multiple backgrounds)


多重背景,也就是CSS2里background的属性外加origin、clip和size组成的新background的多次叠加,缩写时为用逗号隔开的每组值;用分解写法时,如果有多个背景图片,而其他属性只有一个(例如background-repeat只有一个),表明所有背景图片应用该属性值。

语法缩写如下:

background : [background-color] | [background-image] | [background-position][/background-size] | [background-repeat] | [background-attachment] | [background-clip] | [background-origin],...
可以把上面的缩写拆解成以下形式:
background-image:url1,url2,...,urlN;
background-repeat : repeat1,repeat2,...,repeatN;
backround-position : position1,position2,...,positionN;
background-size : size1,size2,...,sizeN;
background-attachment : attachment1,attachment2,...,attachmentN;
background-clip : clip1,clip2,...,clipN;
background-origin : origin1,origin2,...,originN;
background-color : color;
注意:
  •  用逗号隔开每组 background 的缩写值;
  •  如果有 size 值,需要紧跟 position 并且用 "/" 隔开;
  •  如果有多个背景图片,而其他属性只有一个(例如 background-repeat 只有一个),表明所有背景图片应用该属性值。
  •  background-color 只能设置一个。


新的背景属性

顺序 描述 CSS
background-clip 规定背景的绘制区域。 3
background-origin 规定背景图片的定位区域。 3
background-size 规定背景图片的尺寸。 3