CSS - background-image 屬性



CSS 的background-image屬性允許為元素設定一個或多個背景影像。可以指定影像 URL,並與背景的其他屬性組合,使其更具視覺吸引力。

語法

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

屬性值

描述
url 這指定了所需影像的 URL。對於多個影像,必須提供以逗號分隔的 URL。
nope 這指定不顯示任何影像。預設值。
linear-gradient() 這設定從上到下定義至少兩種顏色的線性漸變背景影像。
radial-gradient() 這設定從中心到邊緣定義至少兩種顏色的徑向漸變背景影像。
initial 這將屬性設定為其初始值。
inherit 這從父元素繼承屬性。

CSS 背景影像屬性示例

下面描述了使用不同值的background-image屬性的一些示例。

設定影像為背景

可以透過指定所需影像的 URL 來設定影像的背景。在以下示例中,使用了花朵影像的 URL。

示例

   <!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。在以下示例中,使用了堆疊在一起的兩張不同影像。

示例

<!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”。

示例

<!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
廣告