CSS Background Color
In this page:
Setting a Background Color
background-color accepts any CSS color value -- named, hex, rgb(), or hsl() -- and fills the element's padding box with that solid color, sitting behind the content but in front of the page background. It's independent from color, which only affects text.
Example: Setting a Background Color
<style>
.box {
background-color: rgb(200, 220, 255);
}
</style>
<div class="box">Filled behind the content, in front of the page background</div>
Background Color and the Box Model
The fill applies to the content area plus padding by default, stopping at the border (unless background-clip changes that), so increasing padding visibly grows the colored area even though the element's declared width/height didn't change.
Example: Background Color and the Box Model
<style>
.box {
background-color: lightblue;
padding: 30px;
}
</style>
<div class="box">More padding visibly grows the colored area</div>
Transparent and Inherited Backgrounds
The default value is transparent, meaning an element with no explicit background-color shows whatever is behind it -- typically its parent's background. Setting background-color: transparent explicitly is occasionally useful to override a color set elsewhere without removing the declaration entirely.
Example: Transparent and Inherited Backgrounds
<style>
.parent {
background-color: yellow;
}
.child {
background-color: transparent;
}
</style>
<div class="parent">
<div class="child">Shows the parent's yellow behind it</div>
</div>
Full-Page Background Color
Setting background-color on the html or body selector colors the entire visible page, since those elements span the full viewport by default. This is the standard way to set an overall page background color or implement a base layer for a dark-mode theme.
Example: Full-Page Background Color
<style>
body {
background-color: #111;
}
p {
color: #eee;
}
</style>
<p>Colors the entire visible page</p>
Background Color with Alpha
Using rgba() or hsla() for background-color lets the fill be semi-transparent, letting whatever is behind the element partially show through -- useful for overlays, hover states, or subtle tinted panels layered over other content.
Example: Background Color with Alpha
<style>
.overlay {
background-color: rgba(0, 0, 0, 0.4);
color: white;
}
</style>
<div class="overlay">Semi-transparent panel over whatever is behind it</div>
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- CSS Colors
- CSS RGB Colors
- CSS HEX Colors
- CSS HSL Colors
- CSS Color Keywords
- CSS Backgrounds
- CSS Background Color
- CSS Background Image
- CSS Background Repeat
- CSS Background Attachment
- CSS Background Shorthand
- CSS Multiple Backgrounds
- CSS Background Size
- CSS Background Origin
- CSS Background Clip
- CSS Borders
- CSS Border Style
- CSS Border Width
- CSS Border Color
- CSS Border Sides
- CSS Border Shorthand