background-size

Definition

The background-size property sets the size of the background images.

.box {
  background-size: 50% 50%;
}

Syntax

.hero {
  background-image: url("/images/team.jpg");
  background-size: cover;
}

Values

  • auto: use the image’s intrinsic size (default).
  • cover: fill the container and crop any overflow.
  • contain: fit the entire image within the container while preserving aspect ratio.
  • <length> or <percentage> pairs: explicit width/height of the background image.

Practical Examples

.hero {
  background: url("https://images.unsplash.com/photo-1521737604893-d14cc237f11d?auto=format&fit=crop&w=800&q=80") center/cover no-repeat;
}

.hero--contain {
  background-size: contain;
}

cover fills the frame while contain ensures the full image remains visible.

HTML
Code
<div class="grid gap-4 sm:grid-cols-2">
  <div class="h-40 rounded-xl border border-slate-200" style="background: url('https://images.unsplash.com/photo-1521737604893-d14cc237f11d?auto=format&fit=crop&w=800&q=80') center/cover no-repeat;"></div>
  <div class="h-40 rounded-xl border border-slate-200" style="background: url('https://images.unsplash.com/photo-1521737604893-d14cc237f11d?auto=format&fit=crop&w=800&q=80') center/contain no-repeat; background-color: rgba(15,23,42,0.08);"></div>
</div>

Tips & Best Practices

  • Use cover for hero sections where cropping is acceptable; ensure important content remains in view with background-position.
  • Combine contain with a background color to fill any letterboxed space.
  • Set explicit sizes (e.g., 100px auto) for repeating patterns to control density.

Accessibility & UX Notes

Keep text overlays legible by pairing large imagery with contrast overlays or blur filters.

Browser Support

Supported in all modern browsers, including mobile. IE9+ supports cover/contain.

  • background-position to adjust focal points.
  • object-fit for similar control on replaced elements.
  • background-repeat in case the image is smaller than the container.

Related posts