CSS - background-size 属性



CSS background-size 属性用于设置元素背景图像的大小。背景图像可以拉伸、约束或保持其原始大小。

语法

background-size: auto | length | cover | contain | initial | inherit;

属性值

描述
auto 背景图像以其原始大小显示。默认值。
长度值 这将设置背景图像的尺寸。第一个值指定宽度,第二个值指定高度;如果只给出一个值,则高度默认为 auto。
百分比 这将背景图像尺寸设置为父元素的百分比。第一个值指定宽度,第二个值指定高度;如果只提供一个值,则高度默认为 auto。
cover 背景图像将调整大小以确保其完全填充容器。在此过程中可能会进行拉伸或裁剪。
contain 背景图像将调整大小以确保其完全可见。
initial 这将属性设置为其初始值。
inherit 这将从父元素继承该属性。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS background-size 属性示例

以下示例将描述 background-size 属性。

图像原始大小

为了显示图像的原始大小而无需任何更改,我们使用 auto 值。这在下面的示例中显示。

示例

Open Compiler
<!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>

使用长度值设置图像大小

要为图像设置特定大小,我们可以指定长度值,宽度将相应调整。这在下面的示例中显示。

示例

Open Compiler
<!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>

使用百分比定义图像大小

图像的大小也可以用百分比来指定,我们指定百分比值来获得所需的大小。这在下面的示例中显示。

示例

Open Compiler
<!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 值。这在下面的示例中显示。

示例

Open Compiler
<!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 值。这在下面的示例中显示。

示例

Open Compiler
<!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>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
background-size 4.0 9.0 4.0 4.1 10.5
css_properties_reference.htm
广告