CSS
🎯 What is background-size?
The background-size property determines:
- how large the background image will appear
- whether it fully covers the element
- whether the entire image stays visible
- or whether the image keeps its original size
🧩 Simple Definition
background-size = controls the size of a background image
💡 Basic Syntax
background-size: value;
🧠 Example
background-size: cover;
👉 The image scales to completely cover the element.
⚙️ Accepted Values
| Value | Description |
|---|---|
| auto | Displays the image at its original size |
| length | Sets custom width and height values |
| % | Sets image size relative to the element |
| cover | Makes the image fully cover the element |
| contain | Makes the entire image fit inside the element |
| initial | Resets to default value |
| inherit | Inherits value from parent element |
🔹 auto
background-size: auto;
👉 The image keeps its original dimensions.
This is the default value.
🔹 Using Fixed Sizes
background-size: 300px 200px;
👉 Sets:
- width → 300px
- height → 200px
🔹Percentage Values
background-size: 50% 50%;
👉 The image size becomes relative to the element’s size.
🔹cover
background-size: cover;
👉 The image scales to completely cover the entire element.
⚠️ Important:
Some parts of the image may be cropped.
This is commonly used in:
- hero sections
- banners
- fullscreen backgrounds
🔹 contain
background-size: contain;
👉 The entire image remains visible inside the element.
⚠️ Important:
Empty space may appear around the image.
No part of the image gets cut off.
⚖️ Difference Between cover and contain
| Property | Result |
|---|---|
| cover | Fills the entire area, may crop image |
| contain | Shows entire image, may leave empty space |
🧩 Practical Examples
1. Fullscreen Background
body {
background-image: url("wallpaper.jpg");
background-size: cover;
}
👉 The image completely fills the page.
2. Entire Image Visible
div {
background-image: url("logo.png");
background-size: contain;
background-repeat: no-repeat;
}
👉 The full image stays visible without cropping.
3. Fixed Image Size
.box {
background-image: url("pattern.png");
background-size: 100px 100px;
}
🎨 Common Usage with Other Properties
background-size is usually combined with:
| Property | Purpose |
|---|---|
| background-image | Defines the image |
| background-repeat | Controls repetition |
| background-position | Controls image position |
🧩 Example
.hero {
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
🧠 Explanation
cover
Makes the image fill the entire area.
center
Centers the image.
no-repeat
Prevents repetition.
⚠️ Important Note
Using very large background images can affect website performance.
For better optimization:
- compress images
- use modern formats like WebP
- avoid unnecessarily large files
