CSS colors bring life to your web pages. They’re used to change the text color, background color, borders, shadows, and much more. In this article, you’ll learn how to use color in CSS with different formats and real examples.
What is CSS Color?
In CSS, the color
property is used to set the text color of an element. Other properties like background-color
, border-color
, and box-shadow
also accept color values.
Basic Example:
p {
color: red;
}
CSS Color Property Usage
CSS Property | Description |
---|---|
color | Text color |
background-color | Background color of elements |
border-color | Border line color |
outline-color | Outline color of elements |
box-shadow | Adds a shadow using a color |
Types of CSS Color Values
1. Named Colors
Use predefined color names like red
, blue
, green
, etc.
h1 {
color: orange;
}
Popular CSS color names: black
, white
, gray
, purple
, teal
, maroon
2. Hexadecimal Colors (#rrggbb
)
A six-digit code that represents red, green, and blue.
body {
background-color: #f4f4f4;
}
#000000
= black#ffffff
= white#ff0000
= red
3. RGB Colors (rgb(r, g, b)
)
Set color using Red, Green, Blue values (0–255).
div {
color: rgb(255, 99, 71); /* Tomato */
}
4. RGBA Colors (with transparency)
Adds opacity using the alpha value (0 to 1).
.box {
background-color: rgba(0, 0, 0, 0.5);
}
5. HSL Colors (hsl(hue, saturation, lightness)
)
More human-readable format.
section {
background-color: hsl(200, 100%, 50%);
}
6. HSLA Colors (with alpha)
Just like HSL, but with transparency.
.overlay {
background-color: hsla(0, 0%, 0%, 0.3);
}
Bonus: CSS Color Variables
You can create reusable colors using CSS variables:
:root {
--main-color: #0066cc;
}
a {
color: var(--main-color);
}
Best Practices for Color in CSS
- Use contrast-friendly colors for accessibility
- Use variables for consistency in themes
- Use transparent colors for overlays
- Test on different devices for visibility