Apply Now Apply Now Apply Now
header_logo
Post thumbnail
HTML

How to Add Background Image in HTML: A Simple Step-by-Step Guide!

By Abhishek Pati

A background image plays an integral role in enhancing the visual aspect of a website or application. Background images are included to grab users’ attention and help them connect with the brand value and message. While writing HTML code, developers add background images to sections such as hero banners, cards, CTAs (call-to-action), or product highlights, depending on their development requirements and objectives.  

But how do they add these background images to their HTML code? This specific blog aims to answer this question by exploring the best techniques and methods with code examples. So, let’s begin our discussion.

Table of contents


  1. Methods to Add Background Image in HTML
    • Inline CSS (style attribute)
    • Internal CSS (<style> tag)
    • External CSS (linked stylesheet)
    • CSS background shorthand property
  2. Output:
    • HTML <img> tag with CSS positioning
  3. Output:
    • CSS pseudo-elements (::before or ::after)
  4. Output:
  5. Best Practices to Add a Background Image in HTML
  6. Conclusion
  7. FAQs
    • What is the best way to add a background image in HTML?
    • Why should we use background-size: cover?
    • What’s the difference between using <img> and CSS background images?

Methods to Add Background Image in HTML

The following are the methods used to add a background image in HTML:

Before understanding all the methods, you can refer to the standard HTML code below, where all these methods will be applied.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Background Image Methods</title>
</head>
<body>

  <!-- 1. Inline CSS -->
  <div id="inline-bg">This is a background image example</div>

  <!-- 2. Internal CSS -->
  <div class="internal-bg">This is a background image example</div>

  <!-- 3. External CSS -->
  <div class="external-bg">This is a background image example</div>

  <!-- 4. CSS background shorthand property -->
  <div class="bg-shorthand">This is a background image example</div>

  <!-- 5. HTML <img> tag with CSS positioning -->
  <div class="img-bg">
    <img src="image.jpg" alt="Background" class="img-position">
    <p>Image Tag with CSS Positioning</p>
  </div>

  <!-- 6. CSS pseudo-elements (::before or ::after) -->
  <div class="pseudo-bg">Pseudo-element Background (::before)</div>
</body>
</html>

Explanation:

In this HTML document, there are seven sections that you can observe; each section represents a different method for adding a background image. Here, each <div> tag has a unique class or ID, allowing separate CSS to be applied without overlap or conflict. Note here that one <img> tag is also used.

Master both HTML and CSS with our comprehensive and insightful course bundle: HTML & CSS

1. Inline CSS (style attribute)

<!-- 1. Inline CSS →

<div id="inline-bg" style="background-image: url('html\ \(1\).jpg'); background-repeat: no-repeat; background-size: cover; background-position: center; height: 500px; width: 50vw; font-size: 30px; text-align: center;">

This is a background image example

    </div>

Explanation:

  • Here, we have added the background image directly within the HTML tag via the style attribute; this approach is known as inline styling. In this code, we have wrapped our image path with url(‘ ‘) for displaying the image on the front-end.
  • background-repeat: no-repeat –>prevents the image from repeating
  • background-size: cover –> sets the image to cover the entire area of the element
  • background-position: center –> centers the image on both axes
  • Additional properties, such as image height and width, font size, and text alignment, are also defined.

Note:

  • px (pixels) and vw (viewport width)/ vh (viewport height) are units used to define sizes.
  • px is a fixed unit that remains constant across all screens.
  • While vw & vh are relative units that vary with the width & height of the browser window (1vw = 1% of the viewport width) and (1vh = 1% of viewport height).

Pro Tip: Avoid using inline CSS when designing or developing scalable websites and applications. Too much inline CSS can make the code messy, leading to maintainability issues.

MDN

2. Internal CSS (<style> tag)

<!-- 2. Internal CSS →

<style>
  .internal-bg {
    background-image: url('html\ \(1\).jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    height: 500px;
    width: 50vw;
    font-size: 30px;
    text-align: center;
  }
</style>

<div class="internal-bg">This is a background image example</div>

Explanation:

  • In this particular code, we have added the background image inside the <style> tag in the same HTML file. This method of applying style to the elements is known as internal CSS.
  • The <div> tag is defined with the class internal-bg, and to apply the styling to this class, we first target it using a dot [.] before that, i.e, “.internal-bg”. In case of ID, you can target it using the # symbol; for example, if id=”internal-bg”, we can target it as “#internal-bg”.
  • Inside this targeted HTML element, we then apply the required background settings. This method keeps the HTML file clean.

Pro Tip:

Always place your <style> tag inside the <head> section of the HTML document. Refer below:

(Code)

Correct placement (inside the <head>):

<head>
  <style>
    /* your CSS here */
  </style>
</head>

____________

(Code)

Wrong placement (outside/after the <head>):

</head>
<style> /* your CSS */ </style>

Also, avoid using internal CSS because it applies styling only to a single page rather than providing it across multiple pages. As a result, the CSS code becomes longer and harder to maintain.

3. External CSS (linked stylesheet)

<!-- 3. External CSS →

<!-- HTML -->
<link rel="stylesheet" href="style.css">
<div class="external-bg">This is a background image example</div>


____________________

<!-- style.css -->
.external-bg {
  background-image: url('html\ \(1\).jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  height: 500px;
  width: 50vw;
  font-size: 30px;
  text-align: center;
}

Explanation:

  • Here, all CSS properties are defined in a separate file, style.css (you can modify the file name as needed).
  • This external CSS file is then linked to the main HTML file using the <link> tag. Inside this tag, the href=”” attribute specifies the path to the CSS file.
  • Among other methods, external CSS is considered the most optimal way to style your web components and layouts, as it allows you to separate HTML content from design, enhancing modularity and maintainability. In addition, you can use a single stylesheet to set the look of multiple pages, saving both time and development effort.

Also Read: Mastering CSS Selectors

4. CSS background shorthand property

<!-- 4. CSS background shorthand property →

<style>
.bg-shorthand {
background: url('html\ \(1\).jpg') no-repeat center/cover;
height: 500px;
width: 50vw;
font-size: 30px;
text-align: center;
}
</style>

<div class="bg-shorthand">This is a background image example</div>

Explanation:

  • Here, if you observe, we have reduced the number of lines of code by not writing a separate line for each property.
  • In this method, we use a shorthand version that combines the image URL, repeat, background-position, and background-size into a single line. It is a practical example of following good coding practices.

Output:

This is the Code Output of Method 1 to Method 4

5. HTML <img> tag with CSS positioning

<!-- 5. HTML <img> tag with CSS positioning →

<style>
    .img-bg {
        width: 100%;
        height: 100%;
}
    .img-bg p {
        font-size: 30px;
        text-align: end;
}
    .img-position {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        object-fit: cover;
        z-index: -1;
}
</style>

    <div class="img-bg">
        <img src="html (1).jpg" alt="Background" class="img-position">
        <p>Image Tag with CSS Positioning</p>
    </div>

Explanation:

  • In this example, “img-bg” is the parent class, and “img-position” is the child class.
  • The parent class sets both height and width to 100%, which is relative to the entire viewport (% relative to the parent; here, the HTML body is the parent of the “img-bg” class).
  • For better comprehension, –> <body> is the parent of “img-bg” class, while –> “img-bg” class is the parent of “img-position” class.
  • The position of “.img-position” is set to absolute, which means it will move with respect to its parent area (the parent’s position must be relative, or else it will take its position from its ancestors, which in this case is the <body>).
  • Once the position is set absolutely, we set the top and left positions to 0 to prevent any gaps.
  • z-index: -1:  places the element behind other elements on the page.

Output:

Observe how the image occupies the entire height and width of the device screen. As discussed above, this happens because both the height and width are set to 100% relative to the parent element’s size.

6. CSS pseudo-elements (::before or ::after)

<!-- 6. CSS pseudo-elements (::before or ::after) →

  .pseudo-bg {
        position: relative;
        height: 100vh;
        font-size: 30px;
}
    .pseudo-bg::before {
        content: "";
        background: url('html\ \(1\).jpg') no-repeat center/cover;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: -1;
}

<div class="pseudo-bg">Pseudo-element Background (::before)</div>

Explanation:

  • In this code, the .pseudo-bg div is set to position: relative so that its ::before pseudo-element can be placed inside it.
  • The :: before creates an empty element (content: “”) that covers the entire div (top: 0; left: 0; right: 0; bottom: 0;).
  • The background image is applied to this pseudo-element, set to cover the area and stay centered.
  • The z-index: -1 places the image behind the text, creating a clean background effect without needing an extra HTML tag.

Output:

Kickstart your web development journey with our free React resource: React eBook

Best Practices to Add a Background Image in HTML

The following are the best practices you should follow while adding a background image in HTML:

  • Use external CSS to keep design separate from HTML.
  • Add background-repeat: no-repeat; background-size: cover; background-position: center; for proper image display.
  • Compress images to improve page loading speed.
  • Use correct image paths (relative or absolute).
  • Add a fallback background color in case the image doesn’t load.
  • Use CSS backgrounds instead of <img> tags for decorative images.

If you’re eager to explore the world of full-stack development and dream of creating real-world software solutions, enroll in HCL GUVI’s IITM Pravartak Certified MERN Full Stack Development Course with AI Integration. Gain hands-on experience with top technologies like Git, MongoDB, Express, React, Node.js, and more. Learn directly from industry professionals and fast-track your way to a rewarding tech career. Don’t wait—connect with our expert counselors today to get started.

Conclusion

Today’s discussion covered various methods for adding background images in HTML and how each method works. We understood the differences between inline, internal, and external CSS and learned that external CSS is best for scalability and clean code. We also explored how positioning and layering work using properties like top, left, and z-index, and reviewed best practices to ensure background images load correctly, look good, and keep the website efficient and organized.

FAQs

What is the best way to add a background image in HTML?

The best approach is to use external CSS, as it keeps your code cleaner, more reusable, and easier to maintain across multiple pages.

Why should we use background-size: cover?

Because it automatically resizes the background image to fill the entire area without stretching or leaving gaps.

MDN

What’s the difference between using <img> and CSS background images?

The <img> tag is for meaningful content images, while CSS background images are used only for decorative or design purposes.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. Methods to Add Background Image in HTML
    • Inline CSS (style attribute)
    • Internal CSS (<style> tag)
    • External CSS (linked stylesheet)
    • CSS background shorthand property
  2. Output:
    • HTML <img> tag with CSS positioning
  3. Output:
    • CSS pseudo-elements (::before or ::after)
  4. Output:
  5. Best Practices to Add a Background Image in HTML
  6. Conclusion
  7. FAQs
    • What is the best way to add a background image in HTML?
    • Why should we use background-size: cover?
    • What’s the difference between using <img> and CSS background images?