如何在單個宣告中設定不同的背景屬性?


CSS(層疊樣式表)是設計網站視覺外觀(包括背景屬性)的強大工具。使用 CSS,可以輕鬆自定義網頁的背景屬性,從而建立獨特的增強使用者體驗的設計。使用單個宣告設定各種背景屬性是一種高效的方法,有助於 Web 開發人員節省時間並使程式碼簡潔。

理解背景屬性

在單個宣告中設定多個背景屬性之前,我們需要了解 CSS 中可用的不同背景屬性以及每個屬性的工作方式。以下是每個屬性的簡要概述。

  • background-color − 此屬性允許設定元素的背景顏色。

  • background-image − 此屬性允許設定元素的背景影像。可以使用影像 URL、線性漸變或徑向漸變設定背景影像。

  • background-repeat − 此屬性允許設定背景影像的重複方式。可以使用 repeat、repeat-x、repeat-y 和 no-repeat 等值進行控制。

  • background-position − 此屬性允許設定背景影像的位置。可以使用 top、bottom、left、right 和 center 等值來定位背景影像。

  • background-size − 此屬性允許設定背景影像的大小。可以使用 Auto、Cover、Include 或以畫素、em 或百分比表示的特定大小值來設定背景影像大小。

  • background-attachment − 此屬性允許設定背景影像是否隨頁面滾動或保持固定。

在一個宣告中設定不同的背景屬性

簡寫屬性“background”用於設定多個背景屬性,它允許在一個宣告中設定背景顏色、影像、重複、位置和附件。

語法

selector {
   background: [background-color] [background-image] [background-repeat] [background-position] [background-size] [background-attachment];
}

此處屬性的順序無關緊要,每個屬性之間用空格隔開。根據設計要求,可以在“background”簡寫屬性中包含其他屬性。

在單個宣告中設定多個背景屬性的示例。

現在,我們將瞭解一些在單個宣告中設定多個背景屬性的示例。

示例 1:設定背景影像

在這裡,我們將使用“background”簡寫屬性來設定 body 元素的背景影像。

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         background: url("https://tutorialspoint.tw/dip/images/black_and_white.jpg") no-repeat center center fixed;
      }
      h3 {
         text-align: center;
      }
   </style>
</head>
<body>
   <h3>Setting a background image in the body element</h3>
</body>
</html>

在上面的示例中,我們設定了 body 元素的背景影像和背景顏色。我們還將背景位置設定為居中,並固定了背景影像,以便在滾動時它不會移動。“no-repeat”屬性確保背景影像不會重複。

示例 2:設定漸變背景

在這裡,我們將使用 background 簡寫屬性來設定 body 元素的漸變背景。

<!DOCTYPE html>
<html>
<head>
   <title>Setting the Gradient Background</title>
   <style>
      body {
         background: linear-gradient(to top, #00cfff, #1e40ff);
      }
      h1,h3 {
         text-align: center;
      }
   </style>
</head>
<body>
   <h1>Welcome to TutorialsPoint</h1>
   <h3>Setting the Gradient Background in the body element</h3>
</body>
</html>

在上面的示例中,我們使用了“linear-gradient”函式來設定漸變背景。“to top”引數指定漸變應從下到上。

示例 3 - 在 div 元素中設定背景影像

在這裡,我們將使用“background”簡寫屬性來設定 div 元素的背景影像。

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         text-align: center;
      }
      div {
         background: lightblue url("https://tutorialspoint.tw/dip/images/einstein.jpg") no-repeat center fixed;
         height:300px;
         width:250px;
         margin:auto;
      }
   </style>
</head>
<body>
   <h2>Setting the Background image for the div element</h2>
   <div></div>
</body>
</html>

在上面的示例中,我們設定了 body 元素的背景影像和背景顏色。我們還將背景位置設定為居中,並固定了背景影像,以便在滾動時它不會移動。

結論

在本文中,我們討論了在單個宣告中設定背景屬性。背景屬性是樣式化網頁的重要組成部分。我們使用簡寫屬性在一個宣告中設定多個背景屬性。“background”簡寫屬性對於節省時間和提高程式碼可讀性非常有用。

更新於:2023年4月12日

224 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.