CSS Color Values
A colour value is a code that names one exact colour. CSS can write a colour value with rgb(), with a hex code, or with hsl().
Write red with rgb()
The rgb() form writes red with numbers. It gives the same colour as the keyword red.
h1 {
color: rgb(255, 0, 0);
}Write a colour with hex
The hex code #2e7d32 sets the box paragraph colour. Its computed colour shows the red, green, and blue amounts.
.box p {
color: #2e7d32;
}Write a colour with hsl()
The hsl() form sets hue, saturation, and lightness. This one gives a dark blue.
#demo {
color: hsl(240, 100%, 25%);
}Add transparency with alpha
The rgba() form adds a fourth value for alpha. An alpha of 0.5 makes the colour half transparent.
p.intro {
color: rgba(255, 0, 0, 0.5);
}Example
h1 {
color: rgb(0, 0, 255);
}
.box p {
color: #2e7d32;
}
#demo {
color: hsl(240, 100%, 25%);
}
li {
color: rgba(128, 0, 0, 0.5);
}Key points
- rgb() value: three numbers for red, green, and blue
- In a hex code, the three pairs give red, green, and blue in order.
- In the short form #rgb, each digit doubles to make the full form.
- hsl() value: hue, saturation, and lightness
- Alpha runs from 0, fully transparent, to 1, fully solid.
- rgb(), hex, and hsl() can all name the same colour.
In this example, the heading uses an rgb() value for blue. The box paragraph uses the hex code #2e7d32. The demo paragraph uses an hsl() value for dark blue. The list items use rgba() with an alpha of 0.5.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does an alpha value of 0 mean?