0
0
CssConceptBeginner · 3 min read

What is background-size cover in CSS: Explanation and Example

The CSS property background-size: cover; makes a background image fill the entire element area while keeping its aspect ratio. It scales the image so that it covers the whole container, possibly cropping parts of the image if needed.
⚙️

How It Works

Imagine you have a photo that you want to use as a background for a box on your webpage. The background-size: cover; rule tells the browser to make the photo big enough to cover the entire box without leaving empty spaces.

It keeps the photo's shape (aspect ratio) the same, so the image doesn't look stretched or squished. If the photo is not the exact same shape as the box, some parts of the photo will be cut off (cropped) to make sure the box is fully covered.

This is like putting a blanket over a bed that is a different size — the blanket stretches enough to cover the whole bed, but some edges might hang over or be tucked in.

💻

Example

This example shows a box with a background image that uses background-size: cover;. The image fills the box completely, even if parts of it are cropped.

css
html, body {
  height: 100%;
  margin: 0;
}
.container {
  width: 300px;
  height: 200px;
  border: 2px solid #333;
  background-image: url('https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=600&q=80');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
Output
<div class="container"></div>
🎯

When to Use

Use background-size: cover; when you want a background image to fill an area completely without stretching it oddly. It is perfect for hero sections, banners, or any container where the background image should look full and visually appealing.

It works well when the exact visible part of the image is not critical because some edges might be cropped. For example, a scenic photo behind a header or a full-page background image.

Key Points

  • Keeps aspect ratio: The image won't look stretched or squished.
  • Fills container: The entire area is covered with the image.
  • May crop image: Some parts of the image might not be visible.
  • Common for backgrounds: Used in banners, hero images, and full backgrounds.

Key Takeaways

background-size: cover; scales the background image to fully cover the container.
It preserves the image's aspect ratio to avoid distortion.
Parts of the image may be cropped to fill the area completely.
Ideal for large background images in headers, banners, or full sections.