CSS background-size
The background-size property controls how large a background image is drawn inside its element. Pick a value below to see it live, or type your own.
The background-size property controls how large a background image is drawn inside its element. Pick a value below to see it live, or type your own.
background-size: auto | cover | contain | <width> <height>;
| Value | What it does |
|---|---|
auto | The image keeps its natural size and repeats if the element is larger (default) |
cover | Scales the image to fill the whole element. Parts of the image may be cut off |
contain | Scales the image so all of it is visible. Empty space may remain around it |
100% 100% | Stretches the image to the exact element size, distorting it if the shapes differ |
50% | Width is half the element; height follows the image's proportions |
120px / 80px 40px | Fixed width, or fixed width and height |
Use cover for hero banners and card images, where filling the space matters more than showing every pixel. Use contain for logos, product photos and diagrams, where nothing may be cropped. Pair either one with background-position: center so the important part stays in view.
.hero {
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
When an element has several background layers, give one size per layer, separated by commas, in the same order as the images:
.banner {
background-image: url("logo.svg"), linear-gradient(135deg, #7c6fff, #ff6fb0);
background-size: 80px, cover;
background-repeat: no-repeat;
background-position: 24px 24px, center;
}
Use background-size: cover together with background-position: center and background-repeat: no-repeat.
With the default size the image tiles to fill the element. Add background-repeat: no-repeat or use cover or contain.
cover keeps the image proportions and crops the overflow, while 100% 100% stretches the image to fit exactly, which can distort it.