Skip to main content

Top level navigation menu

A drawn image of Fredrik Bergqvist in a blue shirt

Convert a hex color value to RGB in CSS

Fredrik Bergqvist

While working on a personal project recently, I had the need to convert a hex value (retrieved from a color input element) into RGB values so I could add some transparency to it.

Previously SASS functions was usually used to acchive something like this, but I don't want to use SASS, so I tried searching for a way to solve this in native, modern CSS. I ran into an article on Picalilli written by Kevin Powell about all the modern color functions in CSS.

The rgb() and hsl() functions actually have a built in way of converting hex values, and, even better, they have support for CSS properties as well!

@property --my-color {
  syntax: "<color>";
  initial-value: #D3494E;
  inherits: true;
}

/* Using 'raw' hex value */
.some-rgb-color {
  color: rgb(from #D3494E r g b);
}

/* Using a variable */
.rgb {
  color: rgb(from var(--my-color) r g b);
}
/* We can also add transpanancy */
.rgb-transparant {
  color: rgb(from var(--my-color) r g b / 0.5)
}

/*hsl works the same way*/
.hsl {
  color: hsl(from var(--my-color) h s l / 0.5)
}

Using HSL we can also create lighter or darker variants of a base color

.hsl-light {
  color: hsl(from var(--my-color) h s 90%)
}
.hsl-dark {
  color: hsl(from var(--my-color) h s 10%)
}

I am really happy with the way CSS is evolving, and these new color functions are a great addition to the language!but failed to find a good solution.

This site is built with Eleventy and hosted on Vercel.

Icons are from Flaticon.

Web components from Nidhugg Web components

Performance stats can be found here: Speedlify