In this section, we will learn what the background-size property is and how to use it in CSS.
CSS background-size Property Definition and Usage
By default, the image we use for the background of an element stretch to its dimension when placed as the background.
For example, if the dimension of that picture is 1280 pixels width and 850 pixels height then no-matter what the dimension of the target element is, the image will stretch to its own dimension which might pass the target element’s dimension as well (width and height)!
So controlling the dimension of a background image, CSS provides a property named `background-size` by which we can control the size of a background image.
CSS background-size Property Syntax
CSS background-size Property Value
For the value of this property, we can use numbers with any CSS supported units.
There are a couple of notes you should remember when using numbers for the value of `background-size`:
- The value we set for this property usually is a pair. The first value specifies the width (horizontal) of the background image and the second value specifies the height (vertical) of that image.
- If we set only one number for the `background-size` it will be used to specify the width of that image and the height is then automatically set (in a way that does not distort the aspect ratio of the background image).
- We can also set the value of just width or height of a background image and set the other to “auto”. In that case, the background image is strictly set in one vector (the one that we declare) and browsers automatically set the other vector so that the aspect ratio of the image is not distorted.
Besides numbers, there are two keywords that can be used for this property as well:
- contain: using this value, browsers will scale a background image enough so the image is completely visible in the background of the target element (Depending on the width and height of the target element, this scaling might be up or down).
Note: this scaling does not distort the aspect ratio of the image. Also, in such a case, the image might not cover the entire background of the target element (if the background-repeat is set to no-repeat of course)
- cover: using this value, browsers will scale an image so it completely covers that background of the target element without the need to repeat the image. In such case the dimension of the image might pass the dimension of the element itself.