Use The Simpler CSS Color Syntax
Published Apr 11, 2021
Table of Contents
CSS Features Are Split Into Modules, and Levels
The CSS specification is a living standard. Instead of shipping large releases that takes years for features to hit browsers, we get them when theyโre ready.
Features of CSS are split into modules, and levels such as CSS Flexbox, or CSS Grid.
The CSS Color Module Level 4 specification adds:
- Commaless syntaxes for the
rgb()
,rgba()
,hsl()
, andhsla()
functions - Allows alpha values in
rgb()
andhsl()
, turningrgba()
andhsla()
into (deprecated) aliases for them - Adds 4, and 8 digits hex color values, where the last digit(s) represents the alpha value
A lot of these features arenโt new, but theyโre not used frequently either.
Hex
Hex codes are probably what youโre used to.
/* hex code */
.element {
color: #008080;
}
/* hex shorthand */
.element {
color: #088;
}
How the shorthand works is that you abbreviate each color channel using one character to represent red, green, and blue values.
For example #008080
can be read as 00 80 80
โ so the shorthand would be #088
.
Did you know you can add opacity to a hex color?
Doing so changes the hex code format from #RRGGBB to #RRGGBBAA (8 digits), or #RGBA (4 digits) for the shorthand.
.element {
/* rgba */
color: rgba(0, 128, 128, 50%);
/* hexa (hex + alpha) */
color: #00808080;
/* hexa shorthand */
color: #0888;
}
Keep in mind the opacity value is represented in hexadecimal.
RGB
If youโre using rgb()
, you can write it like this instead since the former syntax is going to be deprecated.
/* rgb */
.element {
color: rgba(0 128 128);
}
/* rgba */
.element {
color: rgba(0 128 128 / 50%);
}
HSL
I have a strong preference for hsl()
which I plan to cover in another post.
For one it makes it easier to create, and reason about your design system than other values since:
- Hue is just a degree on the color wheel from 0 to 360 (red to blue)
- Saturation is a percentage where 0% is gray, and 100% is the full color
- Lightness is a percentage where 0% is black, and 50% is normal
/* hsl */
.element {
color: hsl(180 100% 25%);
}
/* hsla */
.element {
color: hsla(180 100% 25% / 50%);
}
You can also use decimal values instead of percentages for the opacity, but I prefer to be explicit.
Conclusion
Thanks for reading. โค๏ธ Hope you learned something!