CSS - background-image 属性



CSS 的background-image属性允许为元素设置一个或多个背景图像。可以指定图像 URL,并与背景的其他属性组合,使其更具视觉吸引力。

语法

background-image: url('url') | none | initial | inherit;

属性值

描述
url 这指定了所需图像的 URL。对于多个图像,必须提供以逗号分隔的 URL。
nope 这指定不显示任何图像。默认值。
linear-gradient() 这设置从上到下定义至少两种颜色的线性渐变背景图像。
radial-gradient() 这设置从中心到边缘定义至少两种颜色的径向渐变背景图像。
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-image属性的一些示例。

设置图像为背景

可以通过指定所需图像的 URL 来设置图像的背景。在以下示例中,使用了花朵图像的 URL。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .background-img { background-image: url('/css/images/pink-flower.jpg'); background-repeat: no-repeat; width: 400px; height: 400px; position: relative; border: 5px solid black; color: white; } </style> </head> <body> <h2>CSS background-image property</h2> <div class="background-img">Image</div> </body> </html>

多张图像作为背景

如果要使用多张图像,则应在 url() 中以逗号分隔的值指定图像的 URL。在以下示例中,使用了堆叠在一起的两张不同图像。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .multiple-images { background-image: url('/css/images/logo.png'), url('/css/images/white-flower.jpg'); background-repeat: no-repeat; width: 800px; height: 700px; position: relative; border: 5px solid black; color: white; } </style> </head> <body> <h2>CSS background-image property</h2> <div class="multiple-images"></div> </body> </html>

背景中的颜色过渡

也可以使用线性渐变设置图像的背景。颜色过渡在指定方向的直线上发生。这在下面的示例中进行了演示。

在这里,我们定义了渐变的方向“bottom”,然后是起始和结束颜色“yellow”和“green”。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .linear-gradient { background-image: linear-gradient(to bottom, yellow, green); background-repeat: no-repeat; background-position: center; width: 400px; height: 400px; position: relative; border: 5px solid black; } </style> </head> <body> <h2>CSS background image property</h2> <div class="linear-gradient"> Background image with linear gradient</div> </body> </html>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
background-image 1.0 4.0 1.0 1.0 3.0
css_properties_reference.htm
广告