Backgrounds
Control background color, image, position, and repeat.
Syntax
background: color image repeat position / size;Background properties let you decorate an element:
background-color— a solid fill.background-image— an image or gradient.background-repeat— repeat, no-repeat, repeat-x/y.background-positionandbackground-size— placement and scale.
The background shorthand can set them all in one declaration.
Example
Loading editor…
Press Run to see the result.
When to use it
- A developer sets background-image with background-size: cover on a hero section so the photo fills the full container without stretching.
- A designer uses background-position: center to ensure a product image always shows the subject regardless of container size.
- A developer applies background-repeat: no-repeat with a small icon image to add a decorative watermark in the corner of a card.
More examples
Background color and image
Sets a cover image with a color fallback for when the image hasn't loaded, a common hero-section pattern.
.hero {
background-color: #eef3ff; /* fallback */
background-image: url('hero.jpg');
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}Background shorthand property
Uses the background shorthand to set image, repeat, position, size, and color in one declaration.
.banner {
background: url('pattern.png') repeat top left / 200px 200px #1a1a2e;
}Multiple background layers
Layers a semi-transparent gradient over a photo using multiple background-image values, improving text readability.
.card {
background-image:
linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)),
url('card-photo.jpg');
background-size: cover;
background-position: center;
color: #fff;
}
Discussion