How to Set Color in CSS: Simple Syntax and Examples
To set color in CSS, use the
color property followed by a color value like a name, hex code, or RGB. For example, color: red; changes the text color to red.Syntax
The color property in CSS sets the color of text inside an element. You write it as color: value; where value can be a color name, hex code, RGB, or other color formats.
- color: the CSS property to set text color
- value: the color you want, like
red,#ff0000, orrgb(255,0,0)
css
selector {
color: value;
}Example
This example shows how to set the text color of a paragraph to blue using the color property.
css
p {
color: blue;
}Output
A paragraph with blue text.
Common Pitfalls
Common mistakes when setting color in CSS include:
- Using incorrect color names (like
bleuinstead ofblue). - Forgetting the semicolon
;after the color value. - Setting color on elements that don't contain text (so no visible change).
- Overriding color unintentionally with other CSS rules.
css
/* Wrong: misspelled color name and missing semicolon */ p { color: blu; } /* Correct: proper color name and semicolon */ p { color: blue; }
Quick Reference
| Color Value Type | Example | Description |
|---|---|---|
| Named Color | color: red; | Common color names like red, blue, green |
| Hex Code | color: #ff0000; | Hexadecimal color codes starting with # |
| RGB | color: rgb(255,0,0); | Red, Green, Blue values from 0 to 255 |
| RGBA | color: rgba(255,0,0,0.5); | RGB with alpha for transparency |
| HSL | color: hsl(0, 100%, 50%); | Hue, Saturation, Lightness values |
Key Takeaways
Use the CSS property
color to set text color.Color values can be names, hex codes, RGB, RGBA, or HSL formats.
Always end CSS declarations with a semicolon
;.Check spelling of color names to avoid errors.
Set color on elements that contain visible text for effect.