CSS background-size 属性用于设置元素的背景图像的大小。背景图像可以被拉伸、约束或保持其正常大小。
语法
background-size: auto | length | cover | contain | initial | inherit;
属性值
值 | 描述 |
---|---|
auto | 背景图像以其原始大小显示。默认值。 |
length | 将设置背景图像的尺寸。第一个值指定宽度,第二个值指定高度;如果只给出一个,则高度默认为 Auto。 |
percentage | 将背景图像尺寸设置为父元素的百分比。第一个值指定宽度,第二个值指定高度;如果只提供一个,则高度默认为自动。. |
cover | 调整背景图像的大小以确保其完全填充容器。在此过程中可能会进行拉伸或切碎。 |
contain | 调整背景图像的大小以确保其完全可见。 |
initial | 将属性设置为其初始值。 |
inherit | 将继承父元素的属性。 |
CSS Background Size 属性的示例
以下示例将介绍 background-size 属性。
图像的原始大小
为了在不做任何变化的情况下显示图像的原始大小,我们使用 auto 值。这在下面的示例中显示。
<!DOCTYPE html>
<html>
<head>
<style>
.size-auto {
background-image: url('/css/images/pink-flower.jpg');
background-size: auto;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<h2>CSS background-size property</h2>
<div class="size-auto"></div>
</body>
</html>
使用长度的图像大小
要为图像设置特定大小,我们可以指定长度值,宽度将相应调整。这在下面的示例中显示。
<!DOCTYPE html>
<html>
<head>
<style>
.size-length {
background-image: url('/css/images/pink-flower.jpg');
background-size: 150px;
background-repeat: no-repeat;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<h2>CSS background-size property</h2>
<div class="size-length"></div>
</body>
</html>
使用百分比定义图像大小
图像的大小也可以用百分比来指定,我们指定百分比值以获得所需的大小。这在下面的示例中显示。
<!DOCTYPE html>
<html>
<head>
<style>
.size-percent {
background-image: url('/css/images/pink-flower.jpg');
background-repeat: no-repeat;
background-size: 90%;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<h2>CSS background-size property</h2>
<div class="size-percent"></div>
</body>
</html>
图像的完全可见性
为了将图像的大小设置为尽可能大以适合容器而不裁剪或拉伸,我们使用 contain 值。这在下面的示例中显示。
<!DOCTYPE html>
<html>
<head>
<style>
.size-contain {
background-image: url('/css/images/pink-flower.jpg');
background-size: contain;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<h2>CSS background-size property</h2>
<div class="size-contain"></div>
</body>
</html>
完全填充的图像
为了将图像的大小设置为尽可能小的尺寸,以适应容器而不留空空间,我们使用 cover 值。这在下面的示例中显示。
<!DOCTYPE html>
<html>
<head>
<style>
.size-cover {
background-image: url('/css/images/pink-flower.jpg');
background-size: cover;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<h2>CSS background-size property</h2>
<div class="size-cover"></div>
</body>
</html>
支持的浏览器
属性 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
background-size | 4.0 | 9.0 | 4.0 | 4.1 | 10.5 |