One element can have several background layers. Separate them with commas. The first one in the list is on top.
<style>
.card {
height: 140px;
color: white;
padding: 12px;
background-image:
url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30"><circle cx="15" cy="15" r="9" fill="orange"/></svg>'),
linear-gradient(135deg, #1a5276, #d94a00);
background-repeat: no-repeat, no-repeat;
background-position: right 10px bottom 10px, center;
}
</style>
<div class="card">A dot on top of a gradient.</div>
Each property can have its own comma-separated list, matched to the layers in order.
The background shorthand
You can set most background properties in one declaration:
.hero {
background: #2c3e50 url("images/books.jpg") no-repeat center / cover;
}
The order is flexible except for one rule: position and size are written together with a slash, center / cover. The color, if you include one, is conventionally written first.
| Part | Example |
|---|---|
| Color | #2c3e50 |
| Image | url("images/books.jpg") |
| Repeat | no-repeat |
| Position / size | center / cover |
Careful with shorthand
A shorthand resets every property it covers. If you write background: #fff; after setting background-image, the image is gone, because the shorthand sets the image back to none.
Use shorthand to set, longhand to tweak
background: ... is great when you define the whole thing once. Use single properties like background-size when you only want to change one thing, for example in a media query.Exercise: a hero banner
Write a .hero rule with a dark blue fallback color, a centered image that never repeats, and cover sizing, using the shorthand.
Show a possible solution
.hero {
background: #1a3a5c url("images/hero.jpg") no-repeat center / cover;
}