如何設定網頁的背景圖片?


漂亮的網頁是吸引使用者注意力的有力手段。在本文中,我們將瞭解如何將圖片新增為網頁的背景圖片。

方法

本文將介紹兩種將圖片設定為網頁背景圖片的方法。

  • 使用 background 屬性

  • 使用 CSS

方法 1:使用 background 屬性

我們可以在 body 標籤的 background 屬性 中使用 body 標籤 來設定圖片作為網頁的背景。我們需要在 body 標籤的 background 屬性中指定要設定為背景圖片的 URL 或圖片位置。

語法

<body background = "URL or Path of Image">Body of the Webpage</body>

示例

步驟 1 − 首先,我們將定義 HTML 程式碼。

<!DOCTYPE html>
<html>
<head>
   <title>How to add an image as background image of a web page?</title>
</head>
<body>
   <h4>How to add an image as background image of a web page?</h4>
</body>
</html>

步驟 2 − 現在,我們將編輯 body 標籤,使用本地檔案 image.jpg 作為背景圖片。

<body background="image.jpg">

以下是完整的程式碼:

<!DOCTYPE html>
<html>
<head>
   <title>How to add an image as background image of a web page?</title>
</head>
<body background="image.jpg">
   <h4>How to add an image as background image of a web page?</h4>
</body>
</html>

方法 2:使用 CSS

我們還可以使用 CSS 將任何圖片設定為網頁的背景。為此,我們需要將所需圖片的位置或 URL 指定給 background-image 屬性

語法

body {
   background-image: url(" URL of the Image");
}

示例

步驟 1 − 首先,我們將定義 HTML 程式碼。

<!DOCTYPE html>
<html>
<head>
   <title>How to add an image as background image of a web page?</title>
</head>
<body>
   <h4 style="background-color: white;">How to add an image as background image of a web page?</h4>
</body>
</html>

步驟 2 − 現在,我們將新增 CSS。

<style>
   body{
      background-image: url("https://tutorialspoint.tw/images/logo.png");
   }
</style>

以下是完整的程式碼:

<!DOCTYPE html>
<html>
<head>
   <title>How to add an image as background image of a web page?</title>
   <style>
      body {
         background-image: url("https://tutorialspoint.tw/images/logo.png");
      }
   </style>
</head>
<body>
   <h4 style="background-color: white;">How to add an image as background image of a web page?</h4>
</body>
</html>

結論

在本文中,我們瞭解瞭如何將圖片設定為網頁的背景。我們查看了兩種實現相同目標的不同方法。首先,我們瞭解瞭如何透過使用 background 屬性來完成任務。之後,我們還了解了如何使用 CSS 來完成相同操作。

更新於: 2023-09-09

33K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告