1. css
  2. /properties
  3. /background-size

background-size

Definition

In CSS, the background-size property specifies the size of a background image.

Examples

To display a background image at its original size:

body {
  background-image: url(image.jpg);
  background-size: auto;
}

To stretch a background image to fit the container:

body {
  background-image: url(image.jpg);
  background-size: 100% 100%;
}

To shrink a background image to fit the container:

body {
  background-image: url(image.jpg);
  background-size: 50% 50%;
}

To cover the entire container with a background image:

body {
  background-image: url(image.jpg);
  background-size: cover;
}

To fit a background image inside the container:

body {
  background-image: url(image.jpg);
  background-size: contain;
}

To display a different image on the left and right sides of an element:

body {
  background-image: url(image-left.jpg), url(image-right.jpg);
  background-repeat: no-repeat, no-repeat;
  background-size: 50% auto, 50% auto;
  background-position: left, right;
}

Values

ValueDescription
autoThe background image is displayed at its original size. This is the default value.
lengthThe background image is stretched or shrunk to the specified length.
coverThe background image is scaled to cover the entire container.
containThe background image is scaled to fit inside the container.
initialSets the property to its default value.
inheritInherits the property from the parent element.

Best Practices

  • Use the contain or cover values to ensure that your background images look good on different devices and screen sizes. These values preserve the aspect ratio of the image and automatically adjust the size to fit the container.
  • Avoid using the auto value unless you have a specific reason to do so. This value may cause the background image to be distorted or cropped if the container has a different aspect ratio than the image.
  • Use the length value sparingly and with caution. Stretching or shrinking the background image may result in a loss of quality or a distorted appearance.
  • Consider the performance impact of using large or high-resolution background images. These images may take longer to load and use more memory, which can affect the performance of your website or web application.

Browser Compatibility

ChromeFirefoxSafariInternet ExplorerMicrosoft EdgeOpera
YesYesYesYesYesYes

However, some older web browsers may not support the background-size property, or they may only support a limited set of values. For example, the cover and contain values are not supported by Internet Explorer 8 and earlier versions.