0
0
CssHow-ToBeginner · 3 min read

How to Set Background Color in CSS: Simple Guide

To set a background color in CSS, use the background-color property followed by a color value like a name, hex code, or RGB. For example, background-color: blue; sets the background to blue.
📐

Syntax

The background-color property sets the background color of an element. You write it inside a CSS rule with a color value.

  • background-color: the property name
  • color value; the color you want to apply (like red, #ff0000, or rgb(255,0,0))
css
selector {
  background-color: color-value;
}
💻

Example

This example shows how to set the background color of a webpage's body to light blue.

css
body {
  background-color: lightblue;
}
Output
The entire page background turns light blue.
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting the semicolon ; after the color value.
  • Using invalid color names or wrong hex codes.
  • Setting background color on elements that have no visible area or are covered by other elements.
css
/* Wrong: missing semicolon */
div {
  background-color: red
}

/* Correct: semicolon included */
div {
  background-color: red;
}
📊

Quick Reference

Color Value TypeExampleDescription
Named Colorbackground-color: blue;Simple color names supported by browsers
Hex Codebackground-color: #00ff00;Six-digit hex code for precise colors
RGBbackground-color: rgb(255, 0, 0);Red, Green, Blue numeric values
RGBAbackground-color: rgba(0, 0, 255, 0.5);RGB with transparency (alpha)

Key Takeaways

Use the background-color property to set an element's background color in CSS.
Color values can be names, hex codes, or RGB/RGBA formats.
Always end CSS declarations with a semicolon to avoid errors.
Make sure the element has visible space to see the background color.
RGBA allows setting transparent background colors.