Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconHow to Add Background Image in HTML? [Step by Step Guide]

How to Add Background Image in HTML? [Step by Step Guide]

Last updated:
21st Apr, 2023
Views
Read Time
9 Mins
share image icon
In this article
Chevron in toc
View All
How to Add Background Image in HTML? [Step by Step Guide]

Introduction to Background Images in HTML

HTML allows users to create web pages that meet dynamic needs. However, the idea of a webpage means more than textual information. In the world of growing interactive digitalisation, webpages also feature audio-visual and visual information to add to the aesthetic and qualitative value of the page. 

This is where the concept of adding background images comes to play. Sometimes, these images are made to go into the page’s background, behind the text. For example, if you are searching for ways to bake a cake online, you will want real-time pictures to assist and encourage you. 

This keeps the reader focused on the text while at the same time enhancing the aesthetic appeal of the website. 

Now, without further ado, let us dive into how to add background image in HTML

Ads of upGrad blog

Understanding HTML Background Images

So what is an HTML background image? It is a visual element used as the background for a particular portion or the entirety of an HTML document. Usually, the HTML body background image is used to set the page’s theme and give its users an idea about the tonality of the website. 

For example, a children’s nursery rhyme website will use colourful pictures in the background, whereas a library website will opt for a more soothing and serene background. 

Here are some key points to understand about HTML background images:

  1. Background Image Property: The background image is set using CSS (Cascading Style Sheets). You can assign it as the background image by specifying an image’s URL or file path.
  2. Element Selection: HTML allows the user to set different background images for different parts or elements of the HTML text. Users can choose one image for the entire webpage, a specific section, or individual elements like <div> containers.
  3. Image Formats and Positioning: To add to the versatility of its background image feature, HTML allows users to incorporate images or visual information of various formats such as JPG, JPEG, PNG, and even GIF, among others. The image(s) can also be positioned as per the user’s needs.
  4. Image Sizing: HTML also allows the user to set the desired size for the image using the background-size property of the CSS. 
  5. Image Repeat: Now, this is an interesting concept. HTML, by default, sets itself to repeat the background image to cover the entire text. However, this property is altered and modified accordingly using CSS properties. 

Check out our free technology courses to upskill yourself

Read our Popular Articles related to Software Development

Using the Background Attribute in HTML

The “background” attribute in HTML answers how to add background image in HTML without CSS. However, due to certain drawbacks, it is now an outdated method and has been entirely replaced by CSS in most systems.

The “background” attribute of HTML is a paradigm designed to allow users to specify an image’s URL or file path to be used as the background for the element. Here’s an example:

<!DOCTYPE html>

<html>

<body style=”background-image: url(‘replace/with/path/to/your/image.jpg’); background-repeat: no-repeat; background-size: cover;”>

  <!– Content of HTML document –>

</body>

</html>

In the example above, “background” is added to the <body> tag, incorporating it into the syntax. The attribute’s value is set to the URL or file path of the desired image. To insert the image, instead of ‘replace/with/path/to/your/image.jpg’, substitute it with the actual URL of your image file. 

A user with a modern browser can still access the “background” attribute. However, it is considered outdated. Using CSS is a more efficient alternative that aims at more control and flexibility when it comes to image properties such as positioning, repeating, and sizing.

Check Out upGrad’s Software Development Courses to select the best-suited course.

Explore Our Software Development Free Courses

Using CSS to Add Background Images

CSS is an HTML attribute that stands for Cascading Style Sheets. It is a style sheet language that requires input about the presentation and visual appearance in HTML or XML. CSS is the paradigm used to provide a detailed description of non-textual elements within a webpage. 

By “non-textual elements”, we mean that CSS does not interfere with the matter of the text. However, it can change the font size, style, colour, and so on. 

Below is the format for using CSS to add background images:

<!DOCTYPE html>

<html>

<head>

  <style>

    body {

      background-image: url(‘path/to/your/image.jpg’);

      background-repeat: no-repeat;

      background-size: cover;

    }

  </style>

</head>

<body>

  <!– Content of your HTML document –>

</body>

</html>

An example of how to set background image in HTML using CSS:

<!DOCTYPE html>

<html>

<head>

  <style>

    h1 {

      colour: grey;

      font-size: 10px;

    }

    p {

      colour: blue;

      font-size: 22px;

    }

  </style>

</head>

<body>

  <h1>Hello World Welcome to Our XYZ Webpage</h1>

  <p>Hi Please Read this Paragraph.</p>

</body>

</html>

In the above example, the CSS styles are defined within the <style> tags in the HTML document’s <head> section.

CSS selectors are used to target specific HTML elements. In this case, the h1 selector selects all <h1> elements and applies the defined styles. The p selector selects all <p> elements and applies different styles.

In-Demand Software Development Skills

Setting the Background Image Properties in CSS

Here’s an example of how to set the background image properties using CSS:

<!DOCTYPE html>

<html>

<head>

  <style>

    body {

      background-image: url(‘path/to/your/image.jpg’);

      background-repeat: no-repeat;

      background-position: centre;

      background-size: cover;

      background-colour: #ffff00;

    }

  </style>

</head>

<body>

  <!– Content of your HTML document –>

</body>

</html>

In this example, the CSS properties for the background image are set as follows:

  • background-image: This attribute specifies the URL or file path of the background image using the url() function. 
  • background-repeat: This function determines the number of times and the image dimensions to be repeated. In this case, no-repeat is used to prevent the image from repeating.
  • background-position: This sets the position of the image with reference to the text in its HTML container. 
  • background-size: This function defines the size of the background image within its container. The cover value scales the image proportionally to cover the entire container.
  • background-colour: Specifies a fallback background colour in case the background image cannot load or is transparent. Here, #ffff00 represents the yellow colour. This is the hexadecimal format of using colours in the CSS method. However, several other ways exist to set the background colour in CSS, such as using named colours, RGB values, or RGBA values.

Besides these general attributes, one can also experiment with CSS functions like background gradient, multiple background images, or even the scroll behaviour of the image. They each have their particular syntax.

Explore our Popular Software Engineering Courses

Using Inline Styles to Add Background Images in HTML

Inline styles are a way to incorporate CSS elements directly into the HTML body using the ‘style’ attribute. This allows us to define CSS styles and values inside the HTML tag.

For example:-

<!DOCTYPE html>

<html>

<head>

  <title>Hello Background</title>

</head>

<body style=”background-image: url(‘insert/url/to/image’); background-repeat: no-repeat; background-size: cover;”>

  <h1>Hello World</h1>

  <p>Hello all read paragraph please</p>

</body>

</html>

Using External Style Sheets to Add Background Images

To add background images using external style sheets, you can follow these steps:

  1. Create a CSS file: Create a separate CSS file with a .css extension. For example, styles.css.
  2. Link the CSS file to your HTML document: In the <head> section of your HTML file, add a <link> tag to link the CSS file. Specify the href attribute as the path to the CSS file and the rel attribute as “stylesheet.” 

Here’s an example:

<!DOCTYPE html>

<html>

<head>

  <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

  <content>

</body>

</html>

  1. Define the background image in the CSS file: Open your CSS file (styles.css) and define the background image properties. For example:

body {

  background-image: url(‘insert/path/or/url/to/image’);

  background-repeat: no-repeat;

  background-size: cover;

}

Save the CSS file: Save the CSS file (styles.css) in the same directory as your HTML file or in a directory accessible to the HTML file.

Tips and Best Practices for Using Background Images in HTML

  1. Choose the right image: Select a high-quality image that suits your design and complements your content. Ensure the image resolution is appropriate for the intended display size and device.
  2. Optimise image size: Optimise your background images to reduce file size without sacrificing quality. You can use image compression tools or save images in appropriate formats (JPEG for photos, PNG for transparent graphics). Smaller image sizes improve webpage loading speed, resulting in a better user experience.
  3. Consider responsiveness: Make your background images responsive to different screen sizes and devices. Use CSS media queries and the background-size property with values like cover or contain to ensure the image scales appropriately.
  4. Use CSS for background styling: Prefer CSS over deprecated HTML attributes for background styling. Use the background-image property to set the image, and utilise other CSS properties like background-repeat, background-position, background-size, and background-colour to control the appearance and behaviour of the background image.
  5. Be mindful of text readability: Ensure your background image doesn’t hinder text legibility. Choose appropriate text colours or use CSS techniques like adding a semi-transparent overlay or applying text shadows to improve readability.
  6. Test on different devices and browsers: Verify that your background images display correctly across various browsers, screen sizes, and devices. Perform thorough testing to ensure a consistent and visually pleasing user experience.
  7. Accessibility considerations: Take accessibility into account by providing alternative text for the background image. This ensures that users who rely on screen readers or have images disabled can still understand the context.
  8. Combine multiple techniques: Experiment with background techniques like gradients, patterns, and image overlays to create unique and visually appealing designs.
  9. Consider performance impact: Be cautious about using multiple large background images on a single page, as it may impact performance. Evaluate the necessity of each background image and optimise accordingly.
  10. Separate style from content: Maintain clean and organised code by separating your CSS styles into external stylesheets or using the <style> tag in the HTML document’s <head>. This improves maintainability and makes it easier to update and manage background images.

Examples of Background Images in HTML

For example, you want to paste the following image as the background of your HTML document:

So you write the following HTML program to incorporate it:

Code text:-

<!DOCTYPE html>

<html>

<head>

<title>Example</title>

<!– Styles –>

<style>

body {

  background-image: url(“https://images.unsplash.com/photo-1483232539664-d89822fb5d3e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cGhvdG8lMjBiYWNrZ3JvdW5kfGVufDB8fDB8fA%3D%3D&w=1000&q=80”);

  background-position: 50% 50%;

  background-repeat: repeat;

  background-color: white;

}

</style>

</head>

<body>

<!– HTML –>

<h3>Full body image</h3>

<p>Haha can see image now to full<code>body</code> element?</p>

Ads of upGrad blog

</body>

</html>

Conclusion

With background images, you can add depth, personality, and creativity to your web design, captivating visitors and making a lasting impression. Whether for the entire body or specific elements, the flexibility of HTML and CSS allows for various approaches. To gain in-depth knowledge of HTML and the exciting world of possibilities it has to offer, upGrad brings you an array of interactive courses. 

If you are interested in pursuing a full-time career in website development, then the Master of Science in Computer Science from LJMU is the best course for you. However, if you are looking for a course that focuses more on the niche of Stack Development, check out the Executive PG Programme in Full Stack Development from IIITB.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

11. What is the difference between inline styles and external style sheets for adding background images?

There are mainly two points of difference between inline and external styles for adding background images. While HTML elements use inline styles directly using the ‘style’ attribute, external style sheets are separate CSS files linked to the HTML document. They use the tag. Secondly, while inline styles might come in handy for quick styling needs, external style sheets are the way to go if the user wants to go for reusability and efficiency.

22. How to set background images in HTML to specific elements only?

To set background images to specific HTML elements, one must directly link them using inline styles. One can also target them using CSS selectors in external style sheets.

33. How to insert background image in HTML using Notepad?

You can follow a few steps to insert a background image in HTML using Notepad. First, create an HTML file, link an external CSS file to it, and set the image path within the body tag. Then, create a separate CSS file defining the background image using the necessary CSS properties. Save both files and open the HTML file in a web browser to see the background image applied.

Explore Free Courses

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas &#038; Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions &#038; Answers For Freshers &#038; Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16878
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas &#038; Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling &#038; Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions &amp; Answers 2024 [For Freshers &amp; Experienced]
44555
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features &#038; Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas &#038; Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon