Skip to content

CSS Colors

As a developer, most of the time we’re simply copying & pasting color values from a design file, but that doesn’t mean that colors are a small topic!

There are several different ways that we can declare color values, with the most common ones that you’ll see being:

  • Hex codes, such as #ff0000
  • rgb() color functions, such as rgb(255 0 0)
  • hsl() color functions, such as hsl(0 100% 50%)
  • Keyword values, such as red

And some of you might have noticed, the four examples above are all for the same color!

There are two properties where we use color values:

  • color
  • background-color

We can lower the opacity of any color quite easily in CSS by declaring an alpha value when using rgb() and hsl().

To do this, after the three color values, we can add a / and then declare the alpha value that we want, with a number between 0 (fully transparent) and 1 (fully opaque).

.rgb-red-50 {
color: rgb(255 0 0 / 0.5);
}
.hsl-red-50 {
color: hsl(0 100% 50% / 0.5);
}

You can also reduce the opacity when using hex codes by adding two more characters to the end.

.hex-red-50 {
color: #ff000080;
}

I don’t see many people who use this, but if ever you come across an 8-digit hex code, at least you’ll know what those extra ones are doing!

If you are copying and pasting values, then hex is perfectly fine.

If you are writing colors yourself, or maybe copy/pasting a starting valuing and wanting to modify it, then I’d suggest using hsl(), as it’s the easiest one to modify.

A quick word on the syntax of hsl() and rgb()

Section titled “A quick word on the syntax of hsl() and rgb()”

You will see examples of both rgb() and hsl() using commas to separate the values. This is part of the old, legacy syntax.

These are the same:

  • rgb(255 0 0)
  • rgb(255, 0, 0)

New color functions, such as color(), oklch() and hwb() don’t support the comma-separated syntax, so I tend to avoid using them in general.

If you use hsl(), you might be used to using values for your colors, like hsl(250deg 50% 75%).

These days, units are optional, so all of these are equivalent:

.all-the-same {
color: hsl(250deg 50% 75%);
color: hsl(250 50% 75%);
color: hsl(250deg 50 75);
color: hsl(250 50 75);
}

During this course, you may notice that I omit the degrees, but tend to include the percentage. Browser support is better, but it’s mostly out of habit.

You may see examples that use hsla() and rgba(). Adding the a used to be required if you wanted to include an alpha value, but browsers haven’t required it since 2018.

Newer color functions like oklch() and lab() don’t have variants that include a in the name, and they don’t support the comma separated syntax, so I’d suggest sticking with space separated without the a for everything.

Additional Resources

If you’d like to dive deeper into some of what’s possible with modern CSS colors, I have written an in-depth article called A pragmatic guide to modern CSS colours that you might enjoy.