CSS background-size

The background-size CSS property sets the size of a background image. The image can be scaled to a fixed or relative size, or fit to the available space in several manners. Then it may be repeated to fill the background area, according to the background-repeat setting.

background-size: size|cover|contain
background-size: 40px 25px;              /* width height */
background-size: 50% 20%;                /* relative to parent */
background-size: 50% auto;               /* set width and preserve ratio */
background-size: 40px 20px, 25px 10px;   /* two images, different sizes */
background-size: cover;                  /* for full page background */

Comma-separated sizes are applied when there are multiple images defined in the background-image list, following the same order. cover is normally used for a full page background (see below). The property used to change the painting area of a background image is background-clip.

Browser Support: Full.

Scaling the Background

Scale the background by giving two length values (px, em, vw...) or percentages for the width and height respectively. Percentages are relative to the parent element's width/height. Comma separate sizes when working with multiple background images:

.example {
background-image: url('soccer.png'), url('baseball.png'); background-repeat: repeat-x; background-position: bottom, top; background-size: 40px 40px, 20px 20px;

Sadly, there's no max-background-size property. Be sure to take into account the maximum size it reaches to avoid nasty pixelated backgrounds.

The auto Keyword

The auto keyword is specially useful when using percentages. Here's what happens if one sets both dimensions in percentages (because width is relative to parent's width and height relative to parent's height):

.example {
background-image: url('oranges.png'); background-size: 20% 20%;

Specify either width or height as a percentage and set the other one to auto for the image to be resized preserving its aspect ratio.

.example {
background-image: url('oranges.png'); background-size: 20% auto;

20% auto is the same as just 20% because the height would default to auto.

cover for Full Page Background

cover scales the image to be as large as possible so that the background area is completely covered (without repeating the image). Some parts of the image may not be visible. cover is specially useful for a full page background.

contain scales the image to be as large as posible while being entirely visible. The image won't cover the full background area without repetition, unless it has the same aspect ratio.


Useful Resources

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>