background-size
Sets the size of the background image: covering everything, fitting entirely, or specific dimensions.
- Initial value
auto auto- Inherited
- No
- Animatable
- yes, as a length or percentage
- Applies to
- all elements
- JavaScript
element.style.backgroundSize = "cover"
Example
#.card-cover {
aspect-ratio: 16 / 9;
background: url("/img/course.webp") center / cover no-repeat;
}<div class="card-cover" style="aspect-ratio: 16 / 9; max-width: 320px; border-radius: 12px; background: url('/collections/covers/vibe-coding.webp') center / cover no-repeat;"></div>Definition and usage
#The background-size property decides how large the background image is. The two most important values are cover and contain, and both preserve the image’s proportions.
cover scales the image up so it covers the whole element, even if part of it gets cropped. contain scales the image so it fits entirely, even if empty strips remain.
You can also give the width and height directly, in pixels or percentages. The auto value for one of the dimensions preserves the proportions.
Syntax
#background-size: auto | cover | contain | <width> <height>?;Values
#- The image’s natural size. A large photo overflows the element.
- The image covers the whole background, the edges may be cropped.
- The whole image is visible, empty strips may remain at the sides.
dimensions
Width of 120px, proportional height.percentages
Dimensions relative to the element, the proportions may be distorted.
Values in practice
#auto
.demo { background-size: auto; }cover
.demo { background-size: cover; }contain
.demo { background-size: contain; }120px auto
.demo { background-size: 120px auto; }50% 100%
.demo { background-size: 50% 100%; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For card covers and banners,
coverwithbackground-position: centeralmost always fits. - In the
backgroundshorthand, the size comes after the position and a slash:center / cover.
Related entries
#- background-imageSets an image or gradient as an element’s background.
- background-positionSets the position of the background image within the element.
- backgroundA shorthand that sets all background properties in one declaration.
- object-fitDecides how an image or video fills a box with different proportions.
Spotted a mistake or missing an example? Write to us.