Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add alpha channel to hex color declared on css variable

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 */
}
like image 213
Jose Varela Avatar asked Aug 27 '18 10:08

Jose Varela


People also ask

How do you add alpha to hex color?

Adding an Alpha Value to CSS Hex CodesUsing an alpha value to update a color's transparency will change the hex code format from #RRGGBB to #RRGGBBAA (where alpha is A ). The first six values (the red, green, and blue ones) remain the same.

How would you apply alpha transparency to a color in CSS?

Transparency using RGBA In addition to RGB, you can use an RGB color value with an alpha channel (RGBA) - which specifies the opacity for a color. An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

How do you add opacity to a color variable in CSS?

You need to make another css variable with full format, in this case it will be hex with opacity: --red-hex-opa: #FF0000F0; And since I for example need to change opacity only in the future or just the color, I would need to change whole color code in hex opacity instead of changing it in one place.

How do you make a transparent hex color?

You can actually apply a hex code color that is transparent. The hex code for transparent white (not that the color matters when it is fully transparent) is two zeros followed by white's hex code of FFFFFF or 00FFFFFF.


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);
}
like image 179
Maggie Cody Avatar answered Sep 30 '22 15:09

Maggie Cody


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.

like image 24
Brett Donald Avatar answered Sep 30 '22 15:09

Brett Donald