background-image

Term side of the Card.
Topic: Background
Unit title: background-image
Categories: Property
Explanation side of the Card

Explanation: The property that sets one or more background images on an element. The images can be URLs, gradients or other formats and they are placed behind the content of the element.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 1.
Availability: 

Example

Wrongcss
.hero {
  background-image: url("hero.jpg");
  color: white;
}
Rightcss
.hero {
  background-color: #1a1a1a;
  background-image:
    linear-gradient(rgb(0 0 0 / 50%), rgb(0 0 0 / 50%)),
    url("hero.jpg");
  color: white;
}

A fallback color and a dark gradient layer keep the white text readable before and after the photo loads.

Common mistakes

  • The image path is wrong because url() is resolved relative to the CSS file, not the HTML page.
  • The image doesn't show because the element has no height.

Key points

  • A background-color is set next to the image, so text stays readable while the image loads or fails.
  • Images that carry meaning use <img> with alt, not background-image.
  • Text over a photo has an overlay gradient or a solid backing that keeps enough contrast.

Interview questions

Can I use multiple background images on one element?

Yes. Separate them with commas; the first image is drawn on top and later ones are drawn below it.

Should I use background-image or img for content images?

Use <img> for images that carry meaning, because it supports alt text, lazy loading and responsive sources. Use background-image for decoration.

Why is my background image not showing?

Usually the url() path is wrong relative to the CSS file, or the element has no size because it is empty.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy