background-size

Sets the size of the background image: covering everything, fitting entirely, or specific dimensions.

Initial value
auto auto
Inherited
No
Animatable
yes, as a length or percentage
Applies to
all elements
JavaScript
element.style.backgroundSize = "cover"
On this page

Example

#
CSS
.card-cover {
  aspect-ratio: 16 / 9;
  background: url("/img/course.webp") center / cover no-repeat;
}
Preview

Definition and usage

#

The background-size property decides how large the background image is. The two most important values are cover and contain, and both preserve the image’s proportions.

cover scales the image up so it covers the whole element, even if part of it gets cropped. contain scales the image so it fits entirely, even if empty strips remain.

You can also give the width and height directly, in pixels or percentages. The auto value for one of the dimensions preserves the proportions.

Syntax

#
Syntax
background-size: auto | cover | contain | <width> <height>?;

Values

#
  • auto

    The image’s natural size. A large photo overflows the element.
  • cover

    The image covers the whole background, the edges may be cropped.
  • contain

    The whole image is visible, empty strips may remain at the sides.
  • 120px auto

    dimensions

    Width of 120px, proportional height.
  • 50% 100%

    percentages

    Dimensions relative to the element, the proportions may be distorted.

Values in practice

#

auto

The image’s natural size. A large photo overflows the element.
.demo { background-size: auto; }

cover

The image covers the whole background, the edges may be cropped.
.demo { background-size: cover; }

contain

The whole image is visible, empty strips may remain at the sides.
.demo { background-size: contain; }

120px auto

Width of 120px, proportional height.
.demo { background-size: 120px auto; }

50% 100%

Dimensions relative to the element, the proportions may be distorted.
.demo { background-size: 50% 100%; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • For card covers and banners, cover with background-position: center almost always fits.
  • In the background shorthand, the size comes after the position and a slash: center / cover.

Related entries

#

Spotted a mistake or missing an example? Write to us.