How To Create Background Image In Html

5 min read

Adding a background image is one of the most fundamental ways to add visual personality to a webpage. Day to day, whether you are building a landing page, a portfolio, or a simple blog, understanding how to control that image—its position, size, and repetition—separates a basic layout from a polished design. This guide walks through the modern CSS techniques required to implement background images effectively, covering everything from the basic syntax to advanced responsive strategies and performance optimization Simple, but easy to overlook..

Worth pausing on this one.

The Core CSS Property: background-image

The primary mechanism for adding a background image in HTML is not an HTML tag, but a CSS property. You apply background-image to any block-level element—typically the <body> for a full-page background or a specific <div>, <section>, or <header> for a contained visual.

The syntax requires the url() function pointing to your image file path.

.hero-section {
  background-image: url('images/hero-background.jpg');
}

Critical Best Practice: Always use relative paths from the location of your CSS file, not your HTML file. If your stylesheet sits in a /css folder and images are in /images at the root, the path needs to traverse up: url('../images/hero-background.jpg').

Controlling Repetition with background-repeat

By default, browsers tile a background image both horizontally and vertically to fill the element. Here's the thing — this is rarely the desired effect for large photographs or illustrations. The background-repeat property gives you control over this tiling behavior.

  • no-repeat: Displays the image once. This is the standard setting for hero banners and full-screen backgrounds.
  • repeat-x: Tiles horizontally only (useful for gradient strips or patterns).
  • repeat-y: Tiles vertically only.
  • repeat: The default; tiles in both directions.
  • space: Tiles the image without clipping, distributing whitespace evenly between tiles.
  • round: Stretches or squishes tiles slightly to fill the space perfectly without gaps.
.hero-section {
  background-image: url('../images/hero.jpg');
  background-repeat: no-repeat;
}

Positioning: The background-position Property

When an image is larger than its container (or vice versa) and no-repeat is set, positioning determines which part of the image remains visible. You can use keywords, percentages, or length units Most people skip this — try not to. Which is the point..

Keywords: top, bottom, left, right, center. Percentages: 50% 50% centers the image. 0% 0% is top-left. 100% 100% is bottom-right. Lengths: 20px 50px moves the image 20px from the left and 50px from the top Small thing, real impact..

/* Centers the image perfectly */
.hero-section {
  background-position: center center; 
  /* Shorthand: background-position: center; */
}

Pro Tip: For responsive designs, center center is usually the safest bet because it ensures the focal point of the image (usually the middle) stays visible as the container resizes And that's really what it comes down to..

Sizing Mastery: background-size

This is arguably the most important property for modern layouts. It dictates how the image scales relative to the container Simple, but easy to overlook..

1. cover (The Hero Standard)

background-size: cover scales the image as large as possible to completely cover the background area while maintaining its aspect ratio. The image will likely be clipped (cropped) on one axis if the container's aspect ratio differs from the image's. This is the go-to value for full-screen hero sections That's the part that actually makes a difference. Less friction, more output..

2. contain (The "Show All" Approach)

background-size: contain scales the image as large as possible while ensuring the entire image fits inside the container. This often results in "letterboxing" (empty space on the sides or top/bottom) if aspect ratios differ. Use this for logos or diagrams where cropping is unacceptable.

3. Explicit Dimensions

You can set specific widths and heights using pixels, em, rem, or percentages Easy to understand, harder to ignore..

/* Width 100%, height auto (maintains aspect ratio) */
background-size: 100% auto;

/* Fixed 300px width, height scales */
background-size: 300px auto;

The Shorthand Property: background

Writing every property individually is verbose. CSS allows a single background shorthand property. The order of values is generally flexible, but a standard convention improves readability:

background: <color> <image> <position> / <size> <repeat> <attachment> <origin> <clip>;

Example of a production-ready hero section:

.hero {
  /* Color fallback loads instantly while image downloads */
  background: #1a1a2e 
              url('../images/hero-desktop.jpg') 
              center center / cover 
              no-repeat 
              fixed; /* Parallax effect (see below) */
  
  /* Ensure minimum height for the background to show */
  min-height: 100vh; 
  display: flex;
  align-items: center;
  justify-content: center;
}

Note the / between position and size. This separator is mandatory in shorthand when defining both background-position and background-size.

The background-attachment Property: Scroll vs. Fixed

This property determines if the background scrolls with the content or stays fixed relative to the viewport.

  • scroll (Default): The background moves with the element's content.
  • fixed: The background stays fixed relative to the browser viewport. This creates a parallax scrolling effect where content slides over the stationary image.
  • local: The background scrolls with the element's content only when the element itself has a scrollbar (overflow scrolling).

Mobile Warning: background-attachment: fixed is notoriously buggy or disabled on iOS Safari and some Android browsers to save GPU memory. It often falls back to scroll automatically. For a reliable parallax effect on mobile, JavaScript-based solutions or transform: translateZ techniques are preferred over pure CSS fixed attachment.

Responsive Background Images: Art Direction & Resolution Switching

A single background-image declaration serves the same file to a 4K desktop monitor and a 375px wide phone. This wastes bandwidth on mobile and looks pixelated on high-DPI (Retina) screens if the source is too small. You have two main CSS-native strategies:

1. Resolution Switching with image-set() (Modern)

The image-set() function allows the browser to choose the most appropriate image based on device pixel ratio (DPR) and connection speed Less friction, more output..

.hero {
  background-image: image-set(
    url('hero-1x.jpg') 1x,
    url('hero-2x.jpg') 2x,
    url('hero-webp.webp') type("image/webp")
  );
  background-size: cover;
  background-position: center;
}

Browser Support: Excellent in modern browsers (Chrome, Firefox, Safari, Edge). Requires a fallback for older browsers That alone is useful..

2. Art Direction with Media Queries (The Classic Way)

Sometimes you don't just need a smaller file; you need a different crop (e.g., a wide landscape shot for desktop vs. a vertical portrait crop for mobile). This requires media queries Most people skip this — try not to. Practical, not theoretical..

/* Mobile First: Vertical Crop */
.hero {
  background-image: url('hero-mobile.jpg');
  background-size: cover;
  background-position: top center; /* Focus on subject's face */
  min-height: 60vh;
}

/
Just Added

Straight from the Editor

Explore the Theme

Good Company for This Post

Thank you for reading about How To Create Background Image In Html. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home