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 */
}
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With