← Back to CSS Course | Chapter 2: Colors & Backgrounds | Lesson 7 of 21

CSS Background Color

background-color is the single property responsible for filling the space behind an element's content and padding with a solid color.

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

css
<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

css
<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

css
<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

css
<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

css
<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>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.