How to set background image of a webpage?


Beautiful webpages are a very strong means of catching user attention. In this article, we are going to see how we can add an image as the background image of a web.

Approach

There are two approaches to setting an image as the webpage's background image, which we will learn in this article. They are −

  • Using background attribute

  • Using CSS

Method 1: Using background attribute

We can use the background attribute in the body tag to set an image as the background of the webpage. We will need to specify the URL or the location of the image which we want to set to the background attribute of the body tag.

Syntax

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

Example

Step 1 − First we will define the HTML code.

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

Step 2 − Now we will edit the body tag to use the local file image.jpg as the background image.

<body background="image.jpg">

Here is the complete code −

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

Method 2: Using CSS

We can also use CSS to set any image as the background of the webpage. To do so, we will need to specify the desired image’s location or URL to the background-image property.

Syntax

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

Example

Step 1 − First we will define the HTML code.

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

Step 2 − Now we will add CSS.

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

Here is the complete code −

<!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.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>

Conclusion

In this article, we saw how we can set an image as the background of a webpage. We looked at two different methods to accomplish the same. First, we saw how through the use of the background attribute we can accomplish the task. Later, we also looked at how we can use CSS to do the same

Updated on: 09-Sep-2023

29K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements