CSS: background size

By Xah Lee. Date: .

background-size

background-size

Controls how big the image is.

values are:

cover
Enlarge the image till it covers the element. Keep aspect ratio. If image is already large enough, do nothing. Result may crop.
contain
Shrink the image till it fits inside the element. Keep aspect ratio. If image already fit, do nothing. Result may repeat or with blank side.
auto
original size. (default)
width height
stretch each side to a length.

example:

  • 100% 100% → stretch both sides. (may distort)
  • 300px 100px → specific dimensions.

each can also be auto.

.x {
 /* fills element, may crop */
 background-size: cover;

 /* fits entirely, may leave empty space or repeat. */
 background-size: contain;

 /* original size */
 background-size: auto;

 /* width height */
 background-size: 50% 200px;
}

example. cover

.cover-dbNWZ {
 background-image: url("i/venus_comb_32m-s289x217.jpg");
 width: 200px;
 height: 200px;
 background-size: cover;
}

example. contain

.contain-dbNWZ {
 background-image: url("i/venus_comb_32m-s289x217.jpg");
 width: 200px;
 height: 200px;
 background-size: contain;
}

example. auto

.auto-dbNWZ {
 background-image: url("i/venus_comb_32m-s289x217.jpg");
 width: 200px;
 height: 200px;
 background-size: auto;
}

CSS. Background