Use background-color on the body or on individual elements, but treat it as a readability decision, not just paint. Compare hex/rgb/hsl formats, watch contrast in dark mode, and avoid common theming pitfalls where a "simple" color change hurts legibility.
How do you change the background color of a page using CSS?
Overview
The background-color property is one of the most fundamental styling tools in CSS. It defines the color that appears behind an element’s content and padding. You can apply it to the <body> element to color the entire page, or to specific containers like <div> or <section> for localized visual effects.
Color Format | Example | Description |
|---|---|---|
Named Colors | background-color: lightblue; | Simple, readable names such as 'red', 'green', or 'lightblue'. |
Hexadecimal | background-color: #ff5733; | Defines color with hex codes representing red, green, and blue values. |
RGB | background-color: rgb(255, 200, 100); | Specifies color using numeric red, green, and blue components (0–255). |
RGBA | background-color: rgba(0, 0, 0, 0.5); | Adds transparency with an alpha channel (0 = transparent, 1 = opaque). |
HSL | background-color: hsl(200, 80%, 50%); | Represents color by hue, saturation, and lightness. |
Example: Coloring the Entire Page
body {
background-color: lavender;
}
This code sets the background of the entire webpage to a soft lavender color by targeting the <body> element.
Example: Coloring a Specific Section
div.hero {
background-color: linear-gradient(to right, #ff9a9e, #fad0c4);
padding: 40px;
border-radius: 12px;
}
Here, a gradient is applied to a <div> with class 'hero'. Although background-color supports solid colors only, CSS allows gradients using the background shorthand.
Accessibility and Design Tips
- Ensure sufficient contrast between text and background colors.
- Light backgrounds are easier for reading long text sections.
- Consistent use of background color enhances brand identity and user experience.
Practical scenario
Set a card background to highlight selected items in a list.
Common pitfalls
- Low contrast with text or icons.
- Forgetting background affects stacking and opacity overlays.
- Using hard-coded colors instead of tokens.
Tokens ease theming but need maintenance. Test contrast and dark mode.
Think of background-color as your page’s canvas color — it sets the tone and mood for everything layered on top.
- Use
background-colorto define background hues for any element. - Supports multiple color systems like HEX, RGB, and HSL.
- Applying it to <body> colors the entire page.
- Combine with gradients or images using the
backgroundshorthand.
Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.