The background-color property in CSS sets the background color of an element or the entire webpage. It supports multiple color formats including named colors, hexadecimal, RGB, RGBA, and HSL. When applied to the <body> element, it changes the entire page’s background color. Backgrounds affect contrast and readability. Test with dark mode and accessibility contrast checks.
How do you change the background color of a page using CSS?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
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.