Paint a background without replacing content
A background can contain a color, one or more images, and gradients. Background images are decorative: they do not provide an HTML alt attribute. Put meaningful diagrams or product images in the document with appropriate alternatives instead.
.hero {
color: white;
background-color: #172554;
background-image:
linear-gradient(rgb(15 23 42 / 0.8), rgb(15 23 42 / 0.5)),
url("images/study-room.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
padding: 4rem 1.5rem;
}The first listed background is painted above later ones. The gradient darkens the photo so white text has a better chance of remaining legible. Still inspect actual contrast; an overlay does not prove every image works. The fallback color remains useful while the image loads or if it fails.
Cover versus contain
cover fills the box and may crop the image. contain fits the whole image and may leave unused space. Neither changes the element's dimensions by itself. Give the container useful content or an explicit sizing rule; a background image alone does not create intrinsic content height.
Gradient experiment
.banner {
background: linear-gradient(120deg, #172554, #1d4ed8);
}
.spotlight {
background: radial-gradient(circle at top left, #dbeafe, #ffffff);
}A gradient is an image generated by CSS. Its direction, stops and shape determine how colors blend. Keep important text readable across the entire painted area.
Path and shorthand pitfalls
In an external stylesheet, a relative image URL resolves relative to that CSS file's URL. A later background shorthand can reset image, position or repeat values. Inspect computed styles and the Network panel before changing unrelated layout rules.
Practice
- Switch cover to contain and compare cropping.
- Temporarily break the image path and ensure the fallback remains readable.
- Move meaningful instructional text out of a background image into real HTML.
- Test narrow and wide viewports, because background cropping changes with aspect ratio.