Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

background-size — sizing background images

The background-size property controls background image dimensions, not element dimensions. Supply explicit sizes, use auto, or fit an image with contain or cover.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

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

background-size sets the size of each background image, not the element. Its initial value is auto auto, and it is not inherited.

In the width/height form, the first value specifies the width and the second specifies the height. If only the width is specified in this form, the height defaults to auto. Lengths and percentages must be nonnegative. Percentages refer to the corresponding dimensions of the background positioning area, usually determined by background-origin. auto uses the image's natural aspect ratio and dimensions when available; it does not always mean the original file size.

contain and cover are standalone sizing modes that determine both image dimensions. contain preserves the natural aspect ratio, if any, and fits the entire image inside the area. cover preserves it and covers the entire area; some image content may be clipped. 100% 100% sets both dimensions independently and can distort the image.

Commas separate sizes for successive background-image layers; a short list repeats, and excess values are ignored. Repetition is controlled separately by background-repeat. In the background shorthand, size follows the position and /, for example background: none center / cover no-repeat.

Examples

<!doctype html>
<meta charset="utf-8">
<title>background-size</title>
<style>
  .sample {
    width: 200px;
    height: 120px;
    background-color: #ddd;
    background-image: linear-gradient(to right, #06c 50%, #fc0 50%);
    background-size: 50% 50%;
    background-position: center;
    background-repeat: no-repeat;
  }
</style>
<div class="sample"></div>

Result

A 200 × 120 CSS-pixel gray rectangle contains a centered 100 × 60 CSS-pixel image: its left half is blue and its right half is yellow.

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources