Color functions
Learn rgb(), hsl() and modern color functions.
The rgb() function
The rgb() function describes a color with red, green and blue channels. Each channel ranges from 0 to 255. rgb(255, 0, 0) is full red, rgb(0, 0, 0) is black.
A fourth value adds transparency: rgba(255, 0, 0, 0.5) is half-transparent red. Modern browsers also accept rgb(255 0 0 / 0.5).
The hsl() function
hsl() describes a color with hue, saturation and lightness. Hue is a degree from 0 to 360: 0 red, 120 green, 240 blue.
Saturation and lightness are written as percentages. hsl(0, 100%, 50%) is vivid red; changing lightness gives pastel or dark shades.
Transparency in color functions
Both rgb() and hsl() accept a fourth value for transparency. Older writing used rgba() and hsla() as separate functions, but modern CSS accepts rgb(20 20 20 / 0.8).
Transparency is a number between 0 (fully transparent) and 1 (fully opaque), or a percentage.
Exercise Color functions for a warning box
Write a .warning selector. Set its background color to hsl(45, 100%, 50%) and its text color to rgb(20, 20, 20).
Show example solution
/* add the warning section */
.warning {
background-color: hsl(45, 100%, 50%);
color: rgb(20, 20, 20);
}
Test yourself
-
What color is rgb(0, 128, 0)?
/* channels are red, green, blue in order */- Blue
- Yellow
- Green
- Purple
Show answer
Green — Correct. The green channel is 128, red and blue are zero; the result is green.
-
Write the green hue
.member { background-color: hsl(____, 100%, 50%); }Show answer
.member { background-color: hsl(120, 100%, 50%); } -
Match each function to its parameters
- rgb()
- Red, green, blue
- hsl()
- Hue, saturation, lightness
- rgba()
- Color and transparency
- #fff
- Hex color