🎓 A1Learner
🔍

CSS Backgrounds

A CSS background is the area behind an element's content. The background-color property paints that area with a colour.

Paint the box

The rule paints the area behind the box content. The text inside the box stays unchanged.

.box {
  background-color: lightblue;
}

Paint the whole page

The body selector stands for the whole page. Its background covers every part of the page.

body {
  background-color: yellow;
}

Two elements, two colours

Each element can carry its own background colour. The heading also sets its text colour in the same rule.

h1 {
  color: white;
  background-color: blue;
}
p.intro {
  background-color: yellow;
}

Example

body {
  background-color: lightyellow;
}
h1 {
  color: white;
  background-color: blue;
}
.box {
  background-color: lightblue;
}
p.intro {
  background-color: yellow;
}

Key points

  • background-color: the property that paints the area behind the content
  • The background fills the element's box, behind its content.
  • The default background-color value is transparent.
  • A transparent background shows whatever sits behind the element.
  • background-color does not pass from a parent element to its children.
  • Use a colour keyword, a hex value or an rgb value for the colour.

In this example, the body rule paints the whole page light yellow. The h1 rule gives the heading white text on a blue background. The box rule paints the box light blue. The intro paragraph rule paints that paragraph yellow.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does the background-color property paint?