Changing Opacity of Hex Colors Using Relative Colors

CSS has a relative new feature for building relative colors based on a source color. This allows you to make small changes to a color value without fully redefining it. One interesting use case for this syntax is changing the opacity of hex colors.

Let’s say we have a color #0ea5e9 (Tailwind’s sky-500), that we want to darken by 50%. We can do this using relative color syntax and the rgb function.

.card {
  background: rgb(from #0ea5e9 r g b / 50%);
}

The r g b portion copies the hex code into it’s RGB components since we aren’t changing the color itself. Then we simply add the / 50% opacity specifier and viola, we’ve changed the opacity of our hex color!

This also works with CSS variables, so if we have our hex code defined as a variable that we can’t modify, no problem!

.card {
  --sky-500: #0ea5e9;
  background: rgb(from var(--sky-500) r g b / 50%);
}