Add alpha channel to hex color declared on css variable

Viewed 6962

Like the title says, i would like to somehow add transparency to a hex color defined in css variable. I have seen solutions in other posts using rgb, but I need hex. Maybe with rgba(), calc() or linear-gradient(), but I didn't reach any result with my attempts.

Can someone help?

I couldn't find any related posts since I am using hex colors and css variables

For example:

:root {
  --blue: #0000ff;
}
 
.blue-with-alpha {
  color: var(--blue)66; /* I am trying to achieve something like this */
}

2 Answers

There are several potential solutions to this:

• adjusting your variable to use rgb values so you can easily add an alpha in CSS:

:root {
   --blue: 0, 0, 255;
}

.blue-with-alpha{
   color: rgba(var(--blue), 0.44);
}

• you could also add alpha as a variable:

:root {
   --blue: 0, 0, 255;
   --alpha: .44;
}

.blue-with-alpha{
   color: rgba(var(--blue), var(--alpha);
}

• using opacity:

:root {
   --blue: #0000ff;
}

.blue-with-alpha {
   color: var(--blue);
   opacity: .44;    
}

• defining a different variable for your highlight:

:root {
   --blue: #0000ff;
   --blue-highlight: #0000ff66;
}

.blue-with-alpha{
   color: var(--blue-highlight);
}

In 2021, alpha values can be included in hex colours.

:root {
  --blue: #0000ff;
  --blue-with-alpha: #0000ff66;
}
 
.blue-with-alpha{
  color: var(--blue-with-alpha);
}

This works in all modern browsers.

Related