Background Color
The background-color property sets a solid color behind an element’s content and padding.
Background Color Example
<style>
.box {
background-color: #ffeaa7;
padding: 20px;
}
</style>
<div class="box">A box with a background color</div>Output
Background Properties
| Property | Purpose |
|---|---|
| background-color | A solid background color |
| background-image | An image, gradient, or pattern |
| background-size | How the image is scaled (cover, contain, or a size) |
| background-position | Where the image is placed within the box |
| background-repeat | Whether the image tiles (repeat, no-repeat) |
Background Image
<style>
.banner {
height: 150px;
background-image: linear-gradient(45deg, #667eea, #764ba2);
background-size: cover;
background-position: center;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
}
</style>
<div class="banner">Banner with a gradient background</div>Output
The background Shorthand
Instead of writing each background property separately, the background shorthand combines several of them into a single declaration.
background Shorthand
.hero {
background: url("hero.jpg") center / cover no-repeat, #333;
}
/* image, position, size, repeat, then a fallback color */background-size: cover vs contain
cover scales the image to fully cover the box, cropping if needed. contain scales it to fit entirely within the box, potentially leaving empty space.
Best Practice
Always set a fallback background-color close to your image’s dominant color, so the layout looks acceptable while the image loads or if it fails to load.