CSS background-size
The CSS background-size
property is used to control the size of a background image within its containing element. It allows you to scale, resize, or control how the background image is displayed to fit the available space.
The background-size
property can take one of the following values:
auto
(default): The background image is displayed at its original size.<length>
: You can specify the width and height of the background image using a specific length value, such aspx
(pixels) orem
.<percentage>
: You can specify the width and height of the background image using a percentage value relative to the containing element’s size.cover
: The background image is scaled to cover the entire element, maintaining its aspect ratio. This may result in cropping of the image if its aspect ratio doesn’t match the element’s aspect ratio.contain
: The background image is scaled to fit within the element while preserving its aspect ratio. This may result in empty space around the image if the element’s aspect ratio is different from the image’s aspect ratio.
Example:
div {
background-image: url('path/to/image.jpg');
background-size: 200px 150px; /* Set width to 200px and height to 150px */
}
In this example, the background image set using the URL will be displayed within the <div>
element with a width of 200 pixels and a height of 150 pixels.
You can also use background-size: cover
or background-size: contain
to create responsive background images that automatically adjust to fit the element’s size:
header {
background-image: url('path/to/header-image.jpg');
background-size: cover; /* Resize to cover the entire header */
}
section {
background-image: url('path/to/section-image.jpg');
background-size: contain; /* Resize to fit within the section */
}
In these examples, the background-size: cover
property ensures that the background image covers the entire header, and the background-size: contain
property ensures that the background image fits within the section.
Using background-size
is particularly useful for responsive design, where you want background images to adjust and scale based on the available screen size or the size of the containing element.
Remember to choose appropriate values for background-size
to achieve the desired visual effect and to ensure that the background images remain clear and visually appealing across different screen sizes and devices.