如何设置网页背景图片?

htmlweb developmentfront end technology更新于 2025/3/25 7:08:17

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

方法

将图片设置为网页背景图片有两种方法,我们将在本文中学习。它们是:-

  • 使用 background 属性

  • 使用 CSS

方法 1:使用 background 属性

我们可以在 body 标签中使用 background 属性将图片设置为网页背景。我们需要指定要设置为 body 标签 background 属性的图片的 URL 或位置。

语法

<body background = "图片的 URL 或路径">网页主体</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://www.cainiaomax.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://www.cainiaomax.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 来实现相同的效果。


相关文章


有用资源