CSS background-size
property specifies the size of the background image. Using the background-size property, the background image can be stretched or contracted to fit in the element’s background.
The size of the background image in the below example is set to 300px wide and 100px tall. Try it out to see how it looks:
Example:
div{ background-image: url('images/road.jpg'); background-repeat: no-repeat; background-size: 300px 100px; }
The background image size can also be specified in percentage(%). The first value represents the width and the second value represents the height. See the example below:
Example:
div{ background-image: url('images/road.jpg'); background-repeat: no-repeat; background-size: 60% 80%; }
CSS Syntax
The background-size
property has the following syntax:
background-size: auto|cover|contain|length|percentage|initial|inherit;
Property Values
The background-size
property accepts the following values:
auto | The background image is set in its original size. This is default. |
cover | The background image stretches or contracts to cover the whole background. |
contain | The background image resizes itself so that it can be fully visible even if the background is too small. |
length(w, h) | Specifies the width and height of the background image. The width and height value can be specified in any valid CSS formats like ‘px’, ’em’, ‘cm’, ‘rem’, etc. c |
percentage(w%,h%) | Specifies the width and height of the background image in percentage(%). The first value specifies the width and the second specifies the height of the background image. If only one value is specified the other automatically sets to ‘auto’. |
initial | Sets the background-size property to its default value(auto). |
inherit | Inherits the background-size from the parent element. |
General Info
Default Value | auto |
Inherited | No |
JavaScript Usage | element.style.backgroundSize = “300px 100px” |
More Examples
If we set the background-size property to cover
, the background image will stretch or contract to cover the full background. See the example below:
Example:
div{ background-image: url('images/sunrise.jpg'); background-repeat: no-repeat; background-size: cover; }
If we set the background-size property to contain
, the background image resizes itself so that it can be fully visible even if the background is too small. See the example below:
Example:
div{ background-image: url('images/sunrise.jpg'); background-repeat: no-repeat; background-size: contain; }
Related Pages
CSS Tutorial: CSS Background