Background Size
What you'll learn: How to control the dimensions of a background image so it perfectly fits your design.
Why Size Matters
You've learned how to add background images, position them, and control whether they repeat. But what happens when your image is too large or too small for its container? That's where background-size comes in—it lets you scale background images to fit exactly how you want them.
The Three Main Approaches
1. cover
Think of cover like wallpaper that always fills the entire wall, even if you need to trim some edges. The image scales up or down to completely fill the container, cropping what doesn't fit.
.hero-section {
background-image: url('landscape.jpg');
background-size: cover;
}
2. contain
With contain, the entire image is always visible—like framing a painting so nothing gets cut off. The image scales to fit within the container, possibly leaving empty space on the sides.
.logo-area {
background-image: url('logo.png');
background-size: contain;
}
3. Explicit Dimensions
You can specify exact width and height using any CSS units you've learned (px, rem, %, etc.). Setting just one value scales proportionally; two values set width and height independently.
.banner {
background-image: url('pattern.png');
background-size: 200px 100px; /* width height */
}
.square {
background-size: 50%; /* scales both proportionally */
}
Choosing the Right Approach
Use cover for hero images where filling the space matters most. Use contain when the entire image must be visible, like logos. Use explicit dimensions for precise control over patterns or decorative elements.
Key Takeaway: background-size controls how background images scale—use cover to fill containers completely, contain to show the full image, or specific dimensions for precise sizing.