CSS Colors
CSS can set colours for text, backgrounds, borders and more. A colour can be written in five main ways.
Colour formats
| Format | Example | Notes |
|---|---|---|
| Name | tomato | About 140 names like red, blue, teal |
| HEX | #ff6347 | Red, green and blue as two hex digits each |
| RGB | rgb(255, 99, 71) | Red, green and blue from 0 to 255 |
| RGBA | rgba(255, 99, 71, 0.5) | Same as RGB with transparency from 0 to 1 |
| HSL | hsl(9, 100%, 64%) | Hue (0-360), saturation and lightness |
h1 { color: tomato; }
h2 { color: #ff6347; }
h3 { color: rgb(255, 99, 71); }
p { background-color: rgba(255, 99, 71, 0.2); }
span { color: hsl(9, 100%, 64%); }
All five show the same colour (the fourth is transparent)
tomato
#ff6347
rgb()
rgba() 0.2
hsl()
Where to use colours
p {
color: #333; /* text colour */
background-color: #f5f5f5; /* background */
border: 2px solid #0073aa; /* border colour */
}
HEX codes
A HEX colour is #RRGGBB. #000000 is black, #ffffff is white, and #ff0000 is pure red. When both digits of each pair are the same, you can use a short form: #fff is #ffffff.
Transparency
Use rgba() or hsla() to make only the colour transparent. To make a whole element transparent, use the opacity property.
Note:
Always keep enough contrast between text and background, so the text is easy to read. Dark grey (#333) on white is better than light grey on white.
Summary
- Colours can be written as names, HEX, RGB, RGBA or HSL.
- Use RGBA for a transparent colour.
- Next: CSS Units.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Write CSS to change the text colour and background of a paragraph |
| Interview Questions & Answers |
|---|
| How to add a background image in CSS? |
| What is the difference between opacity and rgba in CSS? |