CSS background-size Property

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:

autoThe background image is set in its original size. This is default.
coverThe background image stretches or contracts to cover the whole background.
containThe 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’.
initialSets the background-size property to its default value(auto).
inheritInherits the background-size from the parent element.

General Info

Default Valueauto
InheritedNo
JavaScript Usageelement.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

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts

Leave a Comment