How to set a background image
Short answer
Put the file into background-image, and background-size: cover stretches it over the whole block without distortion:
<div style="height: 160px; background-image: url('/media/photo-800x500.jpg'); background-size: cover; background-position: center;"></div>background-position: center chooses which part of the image stays visible when it is cropped.
The shorthand
All background properties fit into one background. The size goes after the position, separated by a slash:
<div style="display: grid; place-items: center; height: 160px; background: steelblue url('/media/photo-800x500.jpg') center / cover no-repeat; color: white; font-size: 24px;">
Spring sale
</div>The steelblue color is visible while the image loads or if it fails to load — and the white text stays readable.
A pattern from a small image
Without cover the image repeats across the whole block. background-size sets the tile size:
<div style="height: 120px; background: url('/media/photo-200x200.jpg') 0 0 / 60px;"></div>Background or img
A background is for decoration. If the image carries meaning — a product photo, a diagram, a portrait — use <img> with alt: a background is invisible to screen readers and search engines.
Common mistake
A background is set on an empty block without a height, and nothing shows. A background has no size of its own: a <div> without content is 0 high, and there is nothing to show the image on. Set height, min-height or aspect-ratio.
Functions used in this recipe
- background-image — One or more background images: files or gradients.
- background-size — The size of a background image.
- background-position — Where the background image is placed inside the block.
- background-repeat — Whether the background image repeats to fill the block.
- background — A shorthand for all background properties: color, image, position, size and repeat.