How to Use Hex Color in CSS: Simple Guide with Examples
In CSS, you use hex colors by writing a
# followed by six hexadecimal digits representing red, green, and blue values, like #ff0000 for red. You apply it to properties like color or background-color to change text or background colors.Syntax
The hex color code starts with a # symbol followed by six hexadecimal digits. These digits are grouped in pairs representing red, green, and blue color values respectively.
- #RRGGBB: Each pair (RR, GG, BB) is a hex number from 00 to FF (0 to 255 in decimal).
- Example:
#00ff00means no red, full green, no blue (bright green).
css
selector {
property: #RRGGBB;
}
/* Example */
p {
color: #1a2b3c;
}Example
This example shows how to set the background color and text color using hex codes in CSS. The background is a soft blue and the text is white.
css
html {
font-family: Arial, sans-serif;
}
body {
background-color: #87ceeb; /* sky blue */
color: #ffffff; /* white */
padding: 20px;
}
h1 {
color: #ff4500; /* orange red */
}Output
A webpage with a sky blue background, white body text, and an orange-red heading.
Common Pitfalls
Common mistakes when using hex colors include:
- Forgetting the
#symbol before the hex digits. - Using fewer or more than six digits (except the shorthand 3-digit form).
- Mixing uppercase and lowercase letters is allowed but be consistent for readability.
- Confusing hex digits with decimal numbers.
Here is a wrong and right example:
css
/* Wrong: missing # */ p { color: ff0000; } /* Right: with # */ p { color: #ff0000; }
Quick Reference
| Hex Code | Color Example | Description |
|---|---|---|
| #000000 | Black | No red, green, or blue |
| #ffffff | White | Full red, green, and blue |
| #ff0000 | Red | Full red only |
| #00ff00 | Green | Full green only |
| #0000ff | Blue | Full blue only |
| #ffff00 | Yellow | Full red and green |
| #00ffff | Cyan | Full green and blue |
| #ff00ff | Magenta | Full red and blue |
Key Takeaways
Always start hex colors with a # followed by six hex digits representing red, green, and blue.
Hex colors can be used in any CSS property that accepts color values like color or background-color.
Common errors include missing the # or using the wrong number of digits.
Hex digits range from 0-9 and a-f (case insensitive).
Use hex colors to precisely control colors in your web design.