The background-size Property
The CSS background-size property defines the size of the background image. This property is vital for creating responsive layouts, as it controls how the image scales relative to the size of the container element.
Syntax and Values
The background-size property can accept lengths, percentages, or keywords.
1. Keyword Values (Most Common)
The two most used values are keywords that dictate image scaling behavior:
| Value | Description | Use Case |
|---|---|---|
cover | Scales the image to be as large as possible while ensuring the entire background area is covered. The image's aspect ratio is maintained, meaning parts of the image may be clipped (cut off) if the aspect ratios don't match. | Hero sections, full-screen backgrounds, or banners where the image must fill the entire space. |
contain | Scales the image to be as large as possible while ensuring the entire image is visible within the container. The aspect ratio is maintained, meaning there may be unused space (letterboxing) around the image if the aspect ratios don't match. | Logos, watermarks, or small icons that must be entirely visible. |
auto | The default. The image uses its original width and height. If only one dimension is auto, the other dimension is calculated automatically to maintain the aspect ratio. | When you want the image to be displayed at its native size. |
2. Length and Percentage Values
You can explicitly set the width and height of the background image.
selector {
background-size: <width> <height>;
}
- Length Units (
px,em,rem, etc.): Sets the background image to a fixed size.background-size: 200px 100px;(Width 200px, Height 100px)
- Percentage Values (
%): Sets the size relative to the container element's dimensions.background-size: 50% auto;(Width is 50% of container, Height maintains aspect ratio)
If you provide only one value (e.g., background-size: 500px;), it sets the width, and the height automatically defaults to auto, maintaining the image's aspect ratio.
Understanding cover vs. contain
The difference between cover and contain is the most important concept in responsive background styling.
| Property | Behavior | Result |
|---|---|---|
cover | Fills the container, but may clip the image. | No empty space, but image clipping. |
contain | Shows the whole image, but may leave space. | Full image visible, but empty space may appear. |
Example Comparison
/* Image fills the area, cutting off top/bottom or sides if needed */
.cover-box {
background-size: cover;
}
/* Image shrinks to fit the smallest dimension, creating unused space */
.contain-box {
background-size: contain;
background-repeat: no-repeat; /* Often used with contain */
}
Interactive background-size Demo
Use the live editor to switch the background-size value between cover, contain, auto, and specific lengths (e.g., 100px 100px). Observe how the image is scaled and whether it fills the box entirely.