如何设置网页的背景图片?


漂亮的网页是吸引用户注意力的有力手段。在本文中,我们将了解如何将图片添加为网页的背景图片。

方法

本文将介绍两种将图片设置为网页背景图片的方法。

  • 使用 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.com/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.com/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+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.