How to Set a Background Color in CSS
background-color fills the area behind an element's content. Set it on body to color the whole page, or on one element to make it stand out.
Syntax
<selector> {
background-color: <color>;
}
| Part | What it does |
|---|---|
<selector> | The element to color, such as body or .note. |
<color> | The background color, such as #fff4ce. |
MDN's background-color page lists the values.
The Example
The example is a page of notices on a light grey page, with one notice on a yellow background.
Step 1: Write the Code
Create a file named index.html in a text editor, such as Visual Studio Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Background color</title>
<style>
body {
background-color: #f3f2f1;
}
.note {
background-color: #fff4ce;
}
</style>
</head>
<body>
<h1>Notices</h1>
<p class="note">The lift is out of order today.</p>
<p>Lunch is at 12:30.</p>
</body>
</html>
Step 2: Open It in a Browser
Double-click index.html. It opens in your browser:

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.
What Happened
- The whole page is light grey,
rgb(243, 242, 241), becausebodyholds the whole page. - The notice is yellow across the full width,
rgb(255, 244, 206). A paragraph is a block, so it's as wide as the page, and its background fills all of it. - The other paragraph shows the grey of the page. Its own background is transparent,
rgba(0, 0, 0, 0), the default.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
The British spelling: background-colour | It isn't a CSS property, so Chromium ignored it and the paragraph stayed transparent | Write background-color |
| Expecting a background on an inline element to fill the line | On a span, the yellow covered only the word: 37 pixels instead of the paragraph's full width | Put the class on a block element, such as p |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| No background appears | The property is misspelled, or the selector doesn't match | Check the spelling and the selector |
| The background covers only the text | The element is inline, like span | Use a block element, or give it display: block |
FAQ
Why does the background fill the whole width?
A p is a block element, and a block takes the whole width of its container. In a window 480 pixels wide, the yellow paragraph was 464 pixels wide: the window minus the page's 8-pixel margins.
What's the default background?
Transparent. A paragraph without a background showed whatever was behind it, here the grey of body.
Conclusion
Set background-color on body for the page, and on any element that needs its own background. Block elements fill the whole line, inline ones only the area behind their text.
Additional Resources
- background-color, on MDN.
