CSS Colors and Backgrounds
Use CSS color properties to style text and surfaces. This beginner guide explains common color formats, solid backgrounds, gradients and background images.
Quick answer: Set text color with color and an element's fill with background-color. CSS accepts named colors, hexadecimal values, RGB and HSL. For a background image, use background-image and choose how it fits with background-size.
Set text and background colors
The color property changes the foreground text color. Use background-color to fill the area behind an element's content and padding.
.notice {
color: #18324a;
background-color: #eaf4ff;
padding: 1rem;
}
Keep text and its background visually distinct. Do not communicate status through color alone; pair a color change with a label, icon or other cue.
Choose a CSS color format
Named colors are quick for simple examples. Hexadecimal colors are common in design tools, while RGB and HSL functions make channels or hue, saturation and lightness explicit.
.palette {
color: navy;
border-color: #2878a8;
background-color: rgb(242 247 250);
}
.accent {
color: hsl(205 68% 34%);
}
Use a consistent format in a project so colors are easy to read and maintain. Modern RGB and HSL syntax can include an alpha value when a translucent color is useful.
Add a gradient background
A gradient is generated by CSS, so it does not require an image file. Linear gradients blend color stops along a line and can be used anywhere a background image is accepted.
.hero {
color: white;
background-image: linear-gradient(120deg, #17324d, #2878a8);
padding: 3rem 1.5rem;
}
Check that text remains easy to read across the entire gradient, including at narrower screen sizes.
Use a background image
Background images work well for decorative surfaces. Provide a fallback color in case the image is slow to load or unavailable. Use cover when the image should fill the area, and expect some cropping as the shape changes.
.photo-banner {
min-height: 18rem;
color: white;
background-color: #18324a;
background-image: url("banner.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
If an image carries information that readers need, add it to the HTML with an <img> element and useful alternative text instead of hiding it in CSS.
Common questions about CSS colors
Which CSS property changes text color?
Use color to set the text and other foreground content color. Use background-color to set the surface behind an element.
What is the difference between a background color and a background image?
A background color paints a solid fallback surface. A background image can display a file or a generated gradient above that surface; the color remains useful if the image cannot be shown.
Should I use an image or a CSS background?
Use an HTML image when it conveys content that should be described to readers. Use a CSS background for decoration that does not need its own text alternative.