CSS Backgrounds
On this page
Multiple Backgrounds
CSS allows you to apply multiple background images to the same element. Each background is separated by a comma, and the first one is drawn on top.
.box {
background-image: url("top.png"), url("pattern.png");
background-position: right bottom, left top;
background-repeat: no-repeat, repeat;
}
You can control each background layer with matching comma-separated values for position, repeat, size, and more.
Background Size
The background-size property controls the size of the background image.
.box {
background-image: url("photo.jpg");
background-size: 300px 200px;
background-repeat: no-repeat;
}
Common keywords:
cover– scales the image to cover the entire element (may crop)contain– scales the image to fit inside the element (may leave empty space)
.hero {
background-image: url("photo.jpg");
background-size: cover;
background-position: center;
}
Background Origin
The background-origin property defines where the background positioning area starts.
padding-box(default) – starts at the padding edgeborder-box– starts at the outer border edgecontent-box– starts at the content area
.box {
border: 10px solid rgba(0,0,0,.2);
padding: 20px;
background-image: url("pattern.png");
background-repeat: no-repeat;
background-origin: content-box;
}
This is especially useful when you want the background to align with the content area instead of the padding or border.
Background Clip
The background-clip property controls how far the background extends.
border-box(default) – background extends under the borderpadding-box– background stops at the padding edgecontent-box– background only behind the content
.box {
border: 10px dashed #333;
padding: 20px;
background: #f2f2f2;
background-clip: padding-box;
}
Tip: background-clip is also used for “text fill” effects with background-clip: text, but that is a separate advanced topic.
Summary
- Multiple backgrounds are added using comma-separated values.
background-sizecontrols image scaling (includingcoverandcontain).background-originsets the starting box for positioning.background-clipcontrols how far the background paints.