background-size: cover scales the image, preserving its aspect ratio, to completely fill the element's background area, cropping any excess that doesn't fit, while background-size: contain instead scales it to fit entirely within the element without cropping, potentially leaving visible empty space, letterboxing, on one axis if the image's and element's aspect ratios don't match. Explicit dimensions, like background-size: 100px 50px, or a single value applying to width with height defaulting to auto, can also be specified directly for precise, non-proportional control, though these don't automatically preserve the image's original aspect ratio the way cover and contain do.
1Understanding Background-size
background-size: cover scales the image, preserving its aspect ratio, to completely fill the element's background area, cropping any excess that doesn't fit, while background-size: contain instead scales it to fit entirely within the element without cropping, potentially leaving visible empty space, letterboxing, on one axis if the image's and element's aspect ratios don't match. Explicit dimensions, like background-size: 100px 50px, or a single value applying to width with height defaulting to auto, can also be specified directly for precise, non-proportional control, though these don't automatically preserve the image's original aspect ratio the way cover and contain do.
Use background-size: cover, paired with background-position: center, as the standard, near-universal pattern for a full-bleed hero or banner background image that should fill its container completely and stay nicely cropped and centered at any size.
.hero {
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
}2Practical Example
Here is a real-world application of Background-size showing how it is used in production CSS code.
.logo-box {
background-image: url("logo.png");
background-size: contain;
background-repeat: no-repeat;
}3Best Practices
Follow these guidelines when working with Background-size:
1. Use background-size: cover for a full-bleed background image that should completely fill its container, accepting some cropping to preserve the image's aspect ratio
2. Use background-size: contain when the entire image must remain fully visible without cropping, accepting potential empty space around it instead
3. Pair background-size with background-position: center for the standard combination used for a responsive, properly-cropped and centered hero background image
Tip: Use background-size: cover, paired with background-position: center, as the standard, near-universal pattern for a full-bleed hero or banner background image that should fill its container completely and stay nicely cropped and centered at any size.
.hero {
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
}