CSS background-size
The background-size property in CSS allows you to specify the size of the background image in relation to the container element. This property can be used to make the background image cover the entire element, contain within the element, or set a specific size for the background image. The background-size property can take different values such as cover, contain, or specific length units like px or %.
Let's see how the background-size property works with some examples:
.container {
width: 300px;
height: 200px;
background-image: url('example.jpg');
background-size: cover;
}
In this example, the background image will cover the entire container element using the value cover for the background-size property. The background image will be scaled to cover the entire container, even if it means clipping the image or repeating it.
.container {
width: 300px;
height: 200px;
background-image: url('example.jpg');
background-size: contain;
}
In this example, the background image will be contained within the container element using the value contain for the background-size property. The background image will be scaled to fit inside the container without distorting the aspect ratio or cropping the image.
You can also specify specific dimensions for the background image using length units like px, em, or %. For example:
.container {
width: 300px;
height: 200px;
background-image: url('example.jpg');
background-size: 100px 50px;
}
In this example, the background image will be set to a specific size of 100 pixels in width and 50 pixels in height within the container element.