DEV Community

Shahab Emami
Shahab Emami

Posted on

Adding opacity to hex colors

We usually use rgba to add opacity to colors.
But recently I was working on a project which all the colors were defined in a theme object with in hex format.
like this:

export type ThemeItem = {
  loader:string;
}

 const darkTheme = {
  loader: "#ffffff",
};

 const lightTheme = {
  loader: "#000000",
};
Enter fullscreen mode Exit fullscreen mode

After a short talk with designer I figured out that every color in the theme object can have different opacity like 10% or 20% ...

For adding this functionality to our design system I added this function according to this stack overflow answer:

export function addOpacityToColor(color: string, opacity: number) {
  const _opacity = Math.round(Math.min(Math.max(opacity || 1, 0), 1) * 255);
  return color + _opacity.toString(16).toUpperCase();
}
Enter fullscreen mode Exit fullscreen mode

and we can use it this way:

addOpacityToColor(theme.green, 0.3)
Enter fullscreen mode Exit fullscreen mode

Here you can read more about adding alpha value to css hex codes

Top comments (0)