background-image
Example
.hero {
background-image: url("hero.jpg");
color: white;
}.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-coloris set next to the image, so text stays readable while the image loads or fails. - Images that carry meaning use
<img>withalt, notbackground-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.