CSS Background Size
- The background-size property is used to define the size of a background image.
- It controls how a background image fits inside an HTML element.
- The most commonly used values are cover and contain.
- CSS background-size helps create responsive and attractive website layouts.
What is CSS background-size?
The CSS background-size property is used to control the dimensions of a background image.
It allows developers to set how large the image should appear inside an element.
This property is commonly used with hero sections, banners, cards, and full-page backgrounds to make images fit properly on different screen sizes.
CSS background-size Syntax
div {
background-size:
cover;
}
CSS background-size Values
auto
Displays the background image in its original size.
cover
Scales the image to completely cover the element area.
contain
Scales the image so the complete image fits inside the element.
Custom Size
Allows setting width and height using pixels or percentages.
Using background-size: cover
The cover value scales the background image to completely cover the element.
Some parts of the image may be cropped if the aspect ratio is different.
section {
background-image:
url("image.jpg");
background-size:
cover;
}
Using background-size: contain
The contain value scales the image so that the complete image is visible
inside the element without cropping.
.box {
background-size:
contain;
}
Setting Custom Background Size
You can define custom width and height values using pixels, percentages, or other CSS units.
div {
background-size:
300px 200px;
}
Using Percentage Values
Percentage values allow the background image size to adjust according to the element size.
body {
background-size:
100% 100%;
}
Difference Between cover and contain
cover
Image covers the complete area but may crop some parts.
contain
Complete image remains visible but empty space may appear.