How to Set Background Size in CSS: Simple Guide
Use the
background-size property in CSS to control the size of a background image. You can set it to values like cover, contain, or specific dimensions such as 100px 50px to adjust how the image fits the element.Syntax
The background-size property accepts these main values:
auto: Default size, original image size.cover: Scales the image to cover the entire element, cropping if needed.contain: Scales the image to fit inside the element without cropping.<width> <height>: Specific size values like pixels, percentages, or other units.
css
background-size: auto | cover | contain | <width> <height>;
Example
This example shows a div with a background image sized using background-size. The image covers the entire box, maintaining aspect ratio but cropping if needed.
css
html, body {
height: 100%;
margin: 0;
}
.container {
width: 300px;
height: 200px;
background-image: url('https://via.placeholder.com/400x300');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
border: 2px solid #333;
}Output
A 300px by 200px box with a background image filling the entire box, cropped if needed, centered inside the box.
Common Pitfalls
Common mistakes when using background-size include:
- Not setting
background-repeat: no-repeat;which causes the image to tile. - Using only one size value without a second value, which can lead to unexpected stretching.
- Forgetting units like
pxor%when specifying sizes.
css
/* Wrong: image repeats and stretches oddly */ .container { background-image: url('https://via.placeholder.com/150'); background-size: 100px; /* Added missing unit */ background-repeat: repeat; /* Added to show default repeat behavior */ } /* Correct: no repeat and proper size with units */ .container { background-image: url('https://via.placeholder.com/150'); background-repeat: no-repeat; background-size: 100px 100px; }
Quick Reference
| Value | Description |
|---|---|
| auto | Use the image's original size |
| cover | Scale image to cover entire element, may crop |
| contain | Scale image to fit inside element, no cropping |
| Set exact size, e.g., 100px 50px or 50% 100% |
Key Takeaways
Use background-size to control how background images fit their container.
Common values are cover, contain, and specific width and height.
Always set background-repeat to no-repeat if you want a single image.
Specify units like px or % when using exact sizes.
Cover fills the area but may crop; contain fits fully but may leave space.