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 | containPreview
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%
width
height
About
cover and contain
coverkeeps the aspect ratio and picks the smallest size that covers the element with no gaps. Whatever overflows is cropped.containkeeps the aspect ratio and picks the largest size that fits the whole image. Gaps remain, and with the defaultbackground-repeatthe 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
autofills the whole area. Give a size when you want a repeating pattern. - Inside the
backgroundshorthand, the size follows the position after a/(background: url(a.png) center / cover). You can’t write/ coverwithout a position. - The preview here lays a sample image with
background-imageand turns repetition off.