在
CSS
中,对背景图片的定位我们使用了
background-position
来调整,不够直观,并且,图片的大小是根据图片的原像素尺寸大小决定的,这些不便在
CSS3
中都有了改善。
1、背景
background-image
background-image
:添加背景图⽚
可添加多个背景,每张图⽚⽤,逗号隔开,前⾯的图⽚会绘制在后⾯的图⽚上
在 CSS3
中,背景的样式作了一些升级调整,让我们可以更好的控制背景元素的样式。这里主要介绍以下几个调整:
- background-size
- background-origin
- background-clip
background-size
background-size
指定背景图像的大小,取代了以前背景图像的大小由实际大小决定。背景图像的大小可以是像素或是百分比大小。
background-size
的语法为:
background-size: length|percentage|cover|contain;
<length>
值,指定背景图⽚⼤⼩,不能为负值。<percentage>
值,指定背景图⽚相对背景区(background positioning area)的百分 ⽐。<auto>
值,以背景图⽚的⽐例缩放背景图⽚。<cover>
值,缩放背景图⽚以完全覆盖背景区。<contain>
值,按原有宽⾼⽐例缩放背景图⽚以完全装⼊背景区。
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
div{
border: 2px solid;
margin: 50px;
width: 600px;
height: 350px;
padding: 50px;
background-image: url('../img/image.png');
/* background-size: 100% 100%; */
/* 如需要查看其它效果,可将注释中的内容替换上面的 background-size */
/* background-size:100px 200px; */
/* background-size:50% 50%; */
/* background-size:cover; */
background-size:contain;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<div></div>
</body>
请自行调整 background-size 的值,观察背景图片的变化。
background-origin
background-origin
:指定背景图⽚的位置
background-origin
的语法为:
padding-box|border-box|content-box;
background-origin
字面理解是背景图片起点的意思,它规定 background-position
属性相对于什么位置来定位。它有三个值:
值 | 描述 |
---|---|
padding-box | 默认值,背景图片从盒模型的 padding-box 左上角开始绘制,即背景图片相对于内边距框来定位,以padding 区域为参考。 |
border-box | 背景图片从盒模型的 border-box 左上角开始绘制,即背景图片相对于边框来定位,以border 区域为参考。 |
content-box | 背景图片从盒模型的 content-box 左上角开始绘制,即背景图片相对于内容框来定位,以content 区域为参考。 |
用上一个例子中的代码来演示 background-origin
不同值的效果,为了对比背景图片的不同的起始位置,我们使用图片的原尺寸,即删除 background-size :
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
/* background-origin: border-box */
div {
border: 2px solid red;
margin: 50px;
width: 600px;
height: 350px;
padding: 50px;
background-image: url('../img/image.png');
background-repeat: no-repeat;
/* background-origin: border-box; */
background-origin: content-box;
/* background-origin: padding-box; */
}
</style>
</head>
<body>
<div></div>
</body>
注意:如果背景不是 no-repeat
,这个属性无效,他会从边框开始显示。
background-clip
background-clip
:指定从哪个位置开始绘制
background-clip
的语法为:
background-clip: border-box|padding-box|content-box;
border-box
:默认值,背景延伸⾄边框外沿(但是在边框下层)。padding-box
:背景延伸⾄内边距(padding
)外沿。不会绘制到边框处。content-box
:背景被裁剪⾄内容区(content box
)外沿。
background-clip
与 background-origin
可以取到的值相同,它们的功能大致相同。但是两者存在一些细微的差别。当它们的值都为 border-box
时,虽然都是从盒模型的边框左上角开始绘制背景图片,但是 background-clip
绘制出来的背景图片不会覆盖左方和上方的边框,而 background-origin
绘制出来的背景图片则会覆盖左方和上方的边框。
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
/* background-origin: border-box */
div {
border: 2px solid red;
margin: 50px;
width: 600px;
height: 350px;
padding: 50px;
background-image: url('../img/image.png');
background-repeat: no-repeat;
background-clip: border-box;
}
</style>
</head>
<body>
<div></div>
</body>