Background

background-size

background-size sets how large a background image is drawn. Give a width and height directly, or use cover and contain to fit the element.

Syntax

<bg-size>#

<bg-size> = [ <length-percentage [0,∞]> | auto ]{1,2} | cover | contain

Preview

Presets
Drag the bottom-right corner to resize

Code

.box {
  background-image: url(/sample.svg);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 50%;
}

Controls

background-size50%
background-size
width
height

About

cover and contain

  • cover keeps the aspect ratio and picks the smallest size that covers the element with no gaps. Whatever overflows is cropped.
  • contain keeps the aspect ratio and picks the largest size that fits the whole image. Gaps remain, and with the default background-repeat the image repeats into them.

Width and height

A single value sets the width and leaves the height auto, keeping the aspect ratio. Two values can distort the image. Percentages are relative to the background area (usually up to the padding), not the image. The initial value is auto, the image’s natural size.

Watch out

  • Gradients have no natural size, so auto fills the whole area. Give a size when you want a repeating pattern.
  • Inside the background shorthand, the size follows the position after a / (background: url(a.png) center / cover). You can’t write / cover without a position.
  • The preview here lays a sample image with background-image and turns repetition off.