使用 "auto" 指定背景图片的大小并以像素为单位:
#example1 {
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: auto;
}
#example2 {
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: 300px 100px;
}
亲自试一试 »
下面有更多 "亲自试一试" 示例。
这个background-size
属性指定背景图片的大小。
此属性可以使用四种不同的语法:关键字语法("auto"、"cover" 和 "contain")、一值语法(设置图片的宽度(高度变为"auto")、双值语法(第一个值:图片宽度,第二个值:高度)和多背景语法(用逗号分隔)。
表中的数字指定完全支持该属性的第一个浏览器版本。
后跟 -webkit-、-moz- 或 -o- 的数字指定使用前缀的第一个版本。
Property | |||||
---|---|---|---|---|---|
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-size: auto|
length|cover|contain|initial|inherit;
Value | Description | Demo |
---|---|---|
auto | Default value. The background image is displayed in its original size | Demo ❯ |
length | Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to "auto". Read about length units | Demo ❯ |
percentage | Sets the width and height of the background image in percent of the parent element. The first value sets the width, the second value sets the height. If only one value is given, the second is set to "auto" | Demo ❯ |
cover | Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges | Demo ❯ |
contain | Resize the background image to make sure the image is fully visible | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
用百分比指定背景图片的大小:
#example1 {
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: 100% 100%;
}
#example2 {
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: 75% 50%;
}
亲自试一试 »
使用 "cover" 指定背景图片的大小:
#example1 {
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: cover;
}
亲自试一试 »
使用 "contain" 指定背景图片的大小:
#example1 {
background: url(mountain.jpg);
background-repeat: no-repeat;
background-size: contain;
}
亲自试一试 »
这里我们有两个背景图片。我们用 "contain" 指定第一个背景图片的大小,用 "cover" 指定第二个背景图片的大小:
#example1 {
background: url(img_tree.gif), url(mountain.jpg);
background-repeat: no-repeat;
background-size: contain, cover;
}
亲自试一试 »
使用不同的背景属性创建"hero" 图片:
.hero-image {
background-image: url("photographer.jpg"); /* The image used */
background-color: #cccccc; /* Used if the image is unavailable */
height: 500px; /* You must set a specified height */
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover; /* Resize the background image to cover the entire container */
}
亲自试一试 »
CSS教程:CSS 背景
HTML DOM 参考:背景大小属性
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!