Trying opacity with sass and css variables - css

I'm loading css variables into my application from db, using a custom function, which will do something like the below code
document.documentElement.style.setProperty(--primaryColor,'#56647B',);
Everything seems to working except when I have to had an opacity to my color.
background-color: rgba($primaryColor, 0.15) is not working.
When I open the console I see background-color: rgba(var(--primaryColor, #56647B), 0.15);
No error on code, this background color it's just not working.
Any clue? Sass seems not to be able to elaborate the var
Thanks for any help
I tried use css var with sass, I'm looking for a workaround or a way to let sass elaborate css variables to work with opacity on components

If you haven't found a solution yet, here are some options/workarounds because as you have found out, it is not possible to do out of the box. You can convert it to either rgb/a or hsl/a colors.
rgb() or rgba() expect 3 or 4 arguments (r, g, b, a) thus the function can not interpret #56647B. Same goes for hsl() and hsla().
SASS has the built-in function rgba() that can handle hex-values.
e.g. in SASS:
.my-class {
background-color: rgba(#123456, 0.5);
}
will be compiled to:
.my-class {
background-color: rgba(18, 52, 86, 0.5);
}
So you could also make sure that on :root you set the colors with
$yourColorHex: #56647B;
--my-color-with-alpha: rgba($yourColorHex, 0.15);
// basic hex to rgb converter
function hexToRGB(hex) {
const hexNormalized = hex.replace('#', '');
const red = parseInt(hexNormalized.substr(0, 2), 16);
const green = parseInt(hexNormalized.substr(2, 2), 16);
const blue = parseInt(hexNormalized.substr(4, 2), 16);
return `${red}, ${green}, ${blue}`;
}
// this handles rgb and rgba values
function hexToRGBA(hex) {
const hexNormalized = hex.replace('#', '');
const red = parseInt(hexNormalized.substr(0, 2), 16);
const green = parseInt(hexNormalized.substr(2, 2), 16);
const blue = parseInt(hexNormalized.substr(4, 2), 16);
const alpha = hexNormalized.substr(6, 2);
let alphaPercentage = '100';
if (!!alpha) {
alphaPercentage = Math.round(parseInt(alpha, 16) / 0xFF * 100);
}
return `${red}, ${green}, ${blue}, ${alphaPercentage}%`;
}
// apply an alpha channel to your hex value
function hexWithAlpha(hex, alpha) {
const hexNormalized = hex.replace('#', '');
const alphaHex = Math.round(alpha * 0xFF).toString(16);
return `#${hexNormalized}${alphaHex}`;
}
// manually convert your hex into an RGB value and separete the values on the css property e.g. #56647B = rgb(86, 100, 123)
document.documentElement.style.setProperty('--col1', '86, 100, 123');
// add an alpha channel to your hex-value manually
// #56647B26 = rgba(86, 100, 123, 0.15);
// https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4
// https://caniuse.com/css-rrggbbaa
document.documentElement.style.setProperty('--col2', '#56647B26');
// convert hex to rgb with a helper function
document.documentElement.style.setProperty('--col3', hexToRGB('#56647B'));
// convert hex to rgba with a helper function
document.documentElement.style.setProperty('--col4', hexToRGBA('#56647B26'));
// add an alpha channel to your hex-value with a helper function
document.documentElement.style.setProperty('--col5', hexWithAlpha('#56647B', 0.15));
:root {
--col1: hotpink;
--col2: hotpink;
--col3: hotpink;
--col4: hotpink;
--col5: hotpink;
}
.container {
display: flex;
flex-flow: row nowrap;
gap: 15px;
}
.box {
width: 100px;
height: 100px;
}
.box-1 {
background-color: rgba(var(--col1), 0.15);
}
.box-2 {
background-color: var(--col2);
}
.box-3 {
background-color: rgba(var(--col3), 0.15);
}
.box-4 {
background-color: rgba(var(--col4));
}
.box-5 {
background-color: var(--col5);
}
<div class="container">
<div class="box box-1">Box 1</div>
<div class="box box-2">Box 2</div>
<div class="box box-3">Box 3</div>
<div class="box box-4">Box 4</div>
<div class="box box-5">Box 5</div>
</div>

Related

SCSS function to change opacity of rgba or hex color [duplicate]

I am designing an app in electron, so I have access to CSS variables. I have defined a color variable in vars.css:
:root {
--color: #f0f0f0;
}
I want to use this color in main.css, but with some opacity applied:
#element {
background: (somehow use var(--color) at some opacity);
}
How would I go about doing this? I am not using any preprocessor, only CSS. I would prefer an all-CSS answer, but I will accept JavaScript/jQuery.
I cannot use opacity because I am using a background image that should not be transparent.
You can't take an existing color value and apply an alpha channel to it. Namely, you can't take an existing hex value such as #f0f0f0, give it an alpha component and use the resulting value with another property.
However, custom properties allow you to convert your hex value into an RGB triplet for use with rgba(), store that value in the custom property (including the commas!), substitute that value using var() into an rgba() function with your desired alpha value, and it'll just work:
:root {
/* #f0f0f0 in decimal RGB */
--color: 240, 240, 240;
}
body {
color: #000;
background-color: #000;
}
#element {
background-color: rgba(var(--color), 0.8);
}
<p id="element">If you can see this, your browser supports custom properties.</p>
This seems almost too good to be true.1 How does it work?
The magic lies in the fact that the values of custom properties are substituted as is when replacing var() references in a property value, before that property's value is computed. This means that as far as custom properties are concerned, the value of --color in your example isn't a color value at all until a var(--color) expression appears somewhere that expects a color value (and only in that context). From section 2.1 of the css-variables spec:
The allowed syntax for custom properties is extremely permissive. The <declaration-value> production matches any sequence of one or more tokens, so long as the sequence does not contain <bad-string-token>, <bad-url-token>, unmatched <)-token>, <]-token>, or <}-token>, or top-level <semicolon-token> tokens or <delim-token> tokens with a value of "!".
For example, the following is a valid custom property:
--foo: if(x > 5) this.width = 10;
While this value is obviously useless as a variable, as it would be invalid in any normal property, it might be read and acted on by JavaScript.
And section 3:
If a property contains one or more var() functions, and those functions are syntactically valid, the entire property’s grammar must be assumed to be valid at parse time. It is only syntax-checked at computed-value time, after var() functions have been substituted.
This means that the 240, 240, 240 value you see above gets substituted directly into the rgba() function before the declaration is computed. So this:
#element {
background-color: rgba(var(--color), 0.8);
}
which doesn't appear to be valid CSS at first because rgba() expects no less than four comma-separated numeric values, becomes this:
#element {
background-color: rgba(240, 240, 240, 0.8);
}
which, of course, is perfectly valid CSS.
Taking it one step further, you can store the alpha component in its own custom property:
:root {
--color: 240, 240, 240;
--alpha: 0.8;
}
and substitute it, with the same result:
#element {
background-color: rgba(var(--color), var(--alpha));
}
This allows you to have different alpha values that you can swap around on-the-fly.
1 Well, it is, if you're running the code snippet in a browser that doesn't support custom properties.
Relative color syntax
With this new CSS ability (css-color-5) which allows color format transformations, it also will also allow adding opacity to any color in any format, for example, to RGB (relative transformations can be done to any other format):
html { --color: blue }
.with-opacity { background: rgb(from var(--color) r g b / 50%) }
(As of writing, not yet available in browsers. Will update once arrives)
👉 Codepen demo
I know the OP isn't using a preprocessor, but I would have been helped if the following information was part of the answer here (I can't comment yet, otherwise I would have commented #BoltClock answer.
If you are using, e.g. scss, the answer above will fail, because scss attempts to compile the styles with a scss-specific rgba()/hsla() function, which requires 4 parameters. However, rgba()/hsla() are also native css functions, so you can use string interpolation to bypass the scss function.
Example (valid in sass 3.5.0+):
:root {
--color_rgb: 250, 250, 250;
--color_hsl: 250, 50%, 50%;
}
div {
/* This is valid CSS, but will fail in a scss compilation */
background-color: rgba(var(--color_rgb), 0.5);
/* This is valid scss, and will generate the CSS above */
background-color: #{'rgba(var(--color_rgb), 0.5)'};
}
<div></div>
Note that string interpolation will not work for non-CSS scss functions, such as lighten(), because the resulting code would not be functional CSS. It would still be valid scss though, so you would receive no error in compilation.
I was in a similar situation, but unfortunately the given solutions did not work for me, as the variables could be anything from rgb to hsl to hex or even color names.
I solved this issue now, by applying the background-color and the opacity to a pseudo :after or :before element:
.container {
position: relative;
}
.container::before {
content: "";
width: 100%;
height: 100%;
position: absolute;
left: 0;
background-color: var(--color);
opacity: 0.3;
}
The styles might need to be changed a little, depending on the element the background should be applied to.
Also it might not work for all situations, but hopefully it helps in some cases, where the other solutions can't be used.
Edit:
I just noticed, that this solution obviously also impacts the text color, as it creates an element in front of the target element and applies a transparent background color to it.
This might be a problem in some cases.
you can use linear-gradient to hack the color:
background: linear-gradient(to bottom, var(--your-color) -1000%, var(--mixin-color), 1000%)
$(() => {
const setOpacity = () => {
$('#canvas').css('--opacity', $('#opacity-value').val())
}
const setColor = () => {
$('#canvas').css('--color', $('#color-value').val());
}
$('#opacity-value').on('input', setOpacity);
$('#color-value').on('input', setColor);
setOpacity();
setColor();
})
#canvas {
width: 100px;
height: 100px;
border: 2px solid #000;
--hack: 10000%;
background: linear-gradient( to bottom, var(--color) calc((var(--opacity) - 1) * var(--hack)), transparent calc(var(--opacity) * var(--hack)));
}
#container {
background-image: linear-gradient(45deg, #b0b0b0 25%, transparent 25%), linear-gradient(-45deg, #b0b0b0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b0b0b0 75%), linear-gradient(-45deg, transparent 75%, #b0b0b0 75%);
background-size: 20px 20px;
background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
padding: 10px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="canvas"></div>
</div>
<hr/>
<input type="range" id="opacity-value" min="0" max="1" step="0.1" value="0.5" />
<input type="color" id="color-value" />
If you use dark and light mode, i use this sample. I prefer separate between colors and rgb colors variable assignment. So i use two each loop. I realise this solution is not dry code. If you want to dry code could you use one loop.
$colors-light: (
white: #fff,
black: #0c0d0e,
orange: #f48024,
green: #5eba7d,
blue: #0077cc,
red: #d1383d,
red-100: #e2474c,
red-200: red,
);
$colors-dark: (
black: #fff,
white: #2d2d2d,
orange: #dd7118,
green: #5eba7d,
blue: #0077cc,
red: #aa1c21,
red-100: #c9292e,
red-200: red,
);
#function hexToRGB($hex) {
#return red($hex), green($hex), blue($hex);
}
#mixin generate_colors($colors) {
// Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--#{$color}: #{$value};
} #else {
--#{$color}: var(--#{$value});
}
}
// RGB Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--RGB_#{$color}: #{hexToRGB($value)};
} #else {
--RGB_#{$color}: var(--RGB_#{$value});
}
}
}
:root {
#include generate_colors($colors-light);
}
[data-theme="dark"] {
#include generate_colors($colors-dark);
}
dry code
#mixin generate_colors($colors) {
// Colors, RGB Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--#{$color}: #{$value};
--RGB_#{$color}: #{hexToRGB($value)};
} #else {
--#{$color}: var(--#{$value});
--RGB_#{$color}: var(--RGB_#{$value});
}
}
}
css Output
:root {
--white: #fff;
--RGB_white: 255, 255, 255;
--black: #0c0d0e;
--RGB_black: 12, 13, 14;
--orange: #f48024;
--RGB_orange: 244, 128, 36;
--green: #5eba7d;
--RGB_green: 94, 186, 125;
--blue: #0077cc;
--RGB_blue: 0, 119, 204;
--red: #d1383d;
--RGB_red: 209, 56, 61;
--red-100: #e2474c;
--RGB_red-100: 226, 71, 76;
--red-200: var(--red);
--RGB_red-200: var(--RGB_red);
}
[data-theme="dark"] {
--black: #fff;
--RGB_black: 255, 255, 255;
--white: #2d2d2d;
--RGB_white: 45, 45, 45;
--orange: #dd7118;
--RGB_orange: 221, 113, 24;
--green: #5eba7d;
--RGB_green: 94, 186, 125;
--blue: #0077cc;
--RGB_blue: 0, 119, 204;
--red: #aa1c21;
--RGB_red: 170, 28, 33;
--red-100: #c9292e;
--RGB_red-100: 201, 41, 46;
--red-200: var(--red);
--RGB_red-200: var(--RGB_red);
}
body {
background-color: var(--white);
}
.colors {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin: 50px 0 0 30px;
}
.box {
width: 100px;
height: 100px;
margin-right: 5px;
}
.black {
background-color: var(--black);
}
.white {
background-color: var(--white);
}
.orange {
background-color: var(--orange);
}
.green {
background-color: var(--green);
}
.blue {
background-color: var(--blue);
}
.red {
background-color: var(--red);
}
.red-200 {
background-color: var(--red-200);
}
.black-rgba {
background-color: rgba(var(--RGB_black), 0.5);
}
.white-rgba {
background-color: rgba(var(--RGB_white), 0.5);
}
.orange-rgba {
background-color: rgba(var(--RGB_orange), 0.5);
}
.green-rgba {
background-color: rgba(var(--RGB_green), 0.5);
}
.blue-rgba {
background-color: rgba(var(--RGB_blue), 0.5);
}
.red-rgba {
background-color: rgba(var(--RGB_red), 0.5);
}
.red-rgba-200 {
background-color: rgba(var(--RGB_red-200), 0.5);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<input type="checkbox" id="dark-switch" name="theme" />
<label for="dark-switch">Dark / Light</label>
</div>
<div class="color-box">
<div class="colors">
<div class="box red-200"></div>
<div class="box black"></div>
<div class="box white"></div>
<div class="box orange"></div>
<div class="box green"></div>
<div class="box blue"></div>
<div class="box red"></div>
</div>
<br>
<h1>RGBA</h1>
<div class="colors">
<div class="box red-rgba-200"></div>
<div class="box black-rgba"></div>
<div class="box white-rgba"></div>
<div class="box orange-rgba"></div>
<div class="box green-rgba"></div>
<div class="box blue-rgba"></div>
<div class="box red-rgba"></div>
</div>
</div>
<script>
const dark_switch = document.getElementById("dark-switch");
dark_switch.addEventListener("change", (e) => {
e.target.checked
? document.documentElement.setAttribute("data-theme", "dark")
: document.documentElement.setAttribute("data-theme", "light");
});
</script>
</body>
</html>
This is indeed possible with CSS. It's just a bit dirty, and you'll have to use gradients. I've coded a small snippet as example, take note that for dark backgrounds, you should use the black opacity, as for light- the white ones.:
:root {
--red: rgba(255, 0, 0, 1);
--white-low-opacity: rgba(255, 255, 255, .3);
--white-high-opacity: rgba(255, 255, 255, .7);
--black-low-opacity: rgba(0, 0, 0, .3);
--black-high-opacity: rgba(0, 0, 0, .7);
}
div {
width: 100px;
height: 100px;
margin: 10px;
}
.element1 {
background:
linear-gradient(var(--white-low-opacity), var(--white-low-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element2 {
background:
linear-gradient(var(--white-high-opacity), var(--white-high-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element3 {
background:
linear-gradient(var(--black-low-opacity), var(--black-low-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element4 {
background:
linear-gradient(var(--black-high-opacity), var(--black-high-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
<div class="element1">hello world</div>
<div class="element2">hello world</div>
<div class="element3">hello world</div>
<div class="element4">hello world</div>
SCSS / SASS
Advantage: You can just use Hex color values, instead to use the 8 Bit for every channel (0-255).
This is how I did it with the initial idea of: https://codyhouse.co/blog/post/how-to-combine-sass-color-functions-and-css-variables
Edit: You could also modify the alpha function to just use #{$color-name}-rgb and omit the generated *-r, *-g, *-b CSS variables.
Result
body {
--main-color: rgb(170, 68, 204);
--main-color-rgb: 170,68,204;
--main-color-r: 170;
--main-color-g: 68;
--main-color-b: 204;
}
.button-test {
// Generated from the alpha function
color: rgba(var(--main-color-r), var(--main-color-g), var(--main-color-b), 0.5);
// OR (you wrote this yourself, see usage)
color: rgba(var(--main-color-rgb), 0.5);
}
Usage:
body {
#include defineColorRGB(--main-color, #aa44cc);
}
.button-test {
// With alpha function:
color: alpha(var(--main-color), 0.5);
// OR just using the generated variable directly
color: rgba(var(--main-color-rgb), 0.5);
}
Mixin and functions
#mixin defineColorRGB($color-name, $value) {
$red: red($value);
$green: green($value);
$blue: blue($value);
#{$color-name}: unquote("rgb(#{$red}, #{$green}, #{$blue})");
#{$color-name}-rgb: $red,$green,$blue;
#{$color-name}-r: $red;
#{$color-name}-g: $green;
#{$color-name}-b: $blue;
}
// replace substring with another string
// credits: https://css-tricks.com/snippets/sass/str-replace-function/
#function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
#if $index {
#return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
#return $string;
}
#function alpha($color, $opacity) {
$color: str-replace($color, 'var(');
$color: str-replace($color, ')');
$color-r: var(#{$color+'-r'});
$color-g: var(#{$color+'-g'});
$color-b: var(#{$color+'-b'});
#return rgba($color-r, $color-g, $color-b, $opacity);
}
You can set specific variable/value for each color - the original and the one with opacity:
:root {
--color: #F00;
--color-opacity: rgba(255, 0, 0, 0.5);
}
#a1 {
background: var(--color);
}
#a2 {
background: var(--color-opacity);
}
<div id="a1">asdf</div>
<div id="a2">asdf</div>
If you can't use this and you are ok with javascript solution, you can use this one:
$(function() {
$('button').click(function() {
bgcolor = $('#a2').css('backgroundColor');
rgb_value = bgcolor.match(/\d+,\s?\d+,\s?\d+/)[0]
$('#a2').css('backgroundColor', 'rgba(' + rgb_value + ', 0.5)');
});
});
:root {
--color: #F00;
}
#a1 {
background: var(--color);
}
#a2 {
background: var(--color);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1">asdf</div>
<div id="a2">asdf</div>
<button>Click to change opacity</button>
:root{
--color: 255, 0, 0;
}
#element{
background-color: rgba(var(--color), opacity);
}
where you replace opacity with anything between 0 and 1
First time posting here..
A simple JavaScript solution
Here's a simple JavaScript function that can add transparency to named color CSS colors like 'red'
Although .setFillColor() is depreciated it is still implemented in some browsers (blink & webkit). If setFillColor() ever gets dropped completely hopefully we'll have Relative color syntax by then.
function addTransparency(color, alpha) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.setFillColor(color, alpha);
return ctx.fillStyle;
}
Usage with CSS variables
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Transparency to a Color</title>
<style>
:root {
--color: lime;
--alpha: 0.5;
}
.test {
background-color: var(--color);
}
</style>
</head>
<body class='test'>
<script>
try{"use strict"
/* Use the getComputedStyle() method to get the current value of the CSS variable --color and the --alpha variable. */
const color = getComputedStyle(document.documentElement).getPropertyValue('--color')||'white'; //added fallback to color white
const alpha = getComputedStyle(document.documentElement).getPropertyValue('--alpha')||1; //added fallback to solid color value of 1
/* Call the addTransparency() function with the color and alpha values as arguments, and store the result in a variable. */
const transparentColor = addTransparency(color, alpha);
/* Use the setProperty() method of the CSSStyleDeclaration interface to set the value of the --color CSS variable to the value of the transparentColor variable. */
document.documentElement.style.setProperty('--color', transparentColor);
function addTransparency(color, alpha) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.setFillColor(color, alpha);
return ctx.fillStyle;
}
}catch(e){document.write(e);}
</script>
</body>
</html>
Ah page refreshed and I lost everything I typed, posting the draft that saved.
If you love hex colors like me there is another solution.
The hex value is 6 digits after that is the alpha value.
00 is 100% transparency 99 is about 75% then it uses the alphabet 'a1-af' then 'b1-bf' ending with 'ff' which is 100% opaque.
:root {
--color: #F00;
}
#element {
background: var(--color)f6;
}
For using rgba() with general css variable, try this:
Declare your color inside :root, but don't use rgb() as other answers do. just write the value
:root{
--color : 255,0,0;
}
Use --color variable using var() as other answers
#some-element {
color : rgba(var(--color),0.5);
}
In CSS you should be able to either use rgba values:
#element {
background: rgba(240, 240, 240, 0.5);
}
or just set the opacity:
#element {
background: #f0f0f0;
opacity: 0.5;
}

CSS mix blend mode / only white or black

Hello I'm currently trying to find a solution to make a sticky text black if the background is white or black in any other case. During my research I found mix blend mode property but it seems very complex to make what I want.
.sticky {
position: -webkit-sticky;
position: sticky;
top: 20px;
color:white;
font-size:60px;
mix-blend-mode: difference;
}
.panel {
height: 80vh;
widht: 100%;
}
.bg-black {
background: black;
}
.bg-red {
background: red;
}
.bg-blue {
background: blue;
}
.bg-green {
background: green;
}
<div class="sticky">
My text
</div>
<div>
<section class="panel"></section>
<section class="panel bg-black"></section>
<section class="panel bg-red"></section>
<section class="panel bg-blue"></section>
<section class="panel bg-green"></section>
</div>
Does someone know a hack or a package that can help me?
Thanks a lot
It is possible to make it with CSS only, by not applying blend mode to the sticky elements, but to the background(::before, ::after) items.
.bg-field::before, .bg-field::after {
background-color: white;
mix-blend-mode: difference;
pointer-events: none;
content: "";
position: absolute;
bottom: 0;
top: 0;
right: 0;
left: 0;
}
.bg-field::before {
z-index: 1;
}
.bg-field::after {
background-color: red;
z-index: -1;
}
Everything inside the bg field (or even outside if its a fixed element) will be colored
I made a code snippet displaying how it works: https://codepen.io/AndrewKnife/pen/XWzBpeN
I'm not sure it's possible with mix-blend-mode, can do what you want with filter and background-clip: text though:
// can ignore this, it's just making the sliders work as R G B
function updateColor() {
const r = document.getElementById('r').value;
const g = document.getElementById('g').value;
const b = document.getElementById('b').value;
document.querySelector('.container').style.background = `rgb(${r},${g},${b}`;
}
.container {
background: white;
}
.contrast-text {
font-size: 50vmin;
background: inherit;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
filter:
sepia(5) /* add some color to grey so the rest works */
saturate(100) /* increase strength of color channels */
invert(1) /* invert the color */
grayscale(1) /* make it grey */
contrast(9); /* make it black/white */
}
<input type="range" onchange="updateColor()" min=0 max=255 value=255 id="r">
<input type="range" onchange="updateColor()" min=0 max=255 value=255 id="g">
<input type="range" onchange="updateColor()" min=0 max=255 value=255 id="b">
<div class="container">
<div class="contrast-text"> Text </div>
</div>
I finally find something great ! It's not as beautiful as mix-blend-mode but it do the job.
I'd prefer to stay 100% css because it require use of ScrollMagic
const controller = new ScrollMagic.Controller();
const sections = document.querySelectorAll('section');
const menu = document.querySelector('.my-text');
sections.forEach((section, index, arr) => {
const trigger = '#' + section.id;
const backgroundColor = window.getComputedStyle(section, null).getPropertyValue('background-color');
const textColor = getContrastYIQ(backgroundColor);
let previousBackgroundColor = backgroundColor;
let previousTextColor = getContrastYIQ(previousBackgroundColor);
if (index >= 1) {
previousBackgroundColor = window.getComputedStyle(arr[index - 1], null).getPropertyValue('background-color');
previousTextColor = getContrastYIQ(previousBackgroundColor);
}
new ScrollMagic.Scene({
triggerElement: trigger,
triggerHook: "onLeave",
offset: -50,
reverse: true
})
.on("enter", function() {
menu.classList.remove(previousTextColor);
menu.classList.add(textColor);
})
.on("leave", function() {
menu.classList.remove(textColor); menu.classList.add(previousTextColor);
})
.addTo(controller);
})
// Color contrast helper function
// https://en.wikipedia.org/wiki/YIQ
function getContrastYIQ(rgb) {
rgb = rgb.substring(4, rgb.length - 1)
.replace(/ /g, '')
.split(',');
const yiq = ((rgb[0] * 299) + (rgb[1] * 587) + (rgb[2] * 114)) / 1000;
return (yiq >= 128) ? 'black' : 'white';
}
section {
min-height: 80vh;
}
.my-text {
position: sticky;
top: 5vh;
color: white;
}
.black {
color: black;
&:before {
background: black;
box-shadow: 0 0.4em 0 0 black, 0 0.80em 0 0 black;
}
}
#s1 {
background-color: black;
}
#s2 {
background-color: white;
}
#s3 {
background-color: #111;
}
#s4 {
background-color: #9f3;
}
#s5 {
background-color: #145;
}
#s6 {
background-color: #f5f;
}
<script ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script>
<div class="my-text">
MY TEXT</div>
<section id="s1">
</section>
<section id="s2"></section>
<section id="s3"></section>
<section id="s4"></section>
<section id="s5"></section>
<section id="s6"></section>

How to make the color of a div change permanently after it has been clicked in react.js

This is the grid that I have
Once a square has been clicked, the color changes to red. - This is done using active class
I would like the change to the background color of the div tag to remain permanent after the square has been clicked.
Code
Board.js
{board.map((row, rowIdx) => (
<div key={rowIdx} className="row">
{row.map((cell, cellIdx) => (
<div key={cellIdx} className="cell"></div>
))}
</div>
))}
Board.css
.row {
height: 30px;
margin: 10px;
transition: transform 0.1s;
}
.cell:hover {
transform: scale(1.4);
}
.cell {
width: 30px;
height: 30px;
outline: 1px solid rgb(134, 154, 189);
display: inline-block;
background-color: seagreen;
margin: 5px;
transition: transform 0.2s;
}
.row :active {
background-color: red;
}
.cell :active { // Does not do anything
background-color: blue;
}
Once another square is clicked, the previosly clicked one does not remain active, you can do this by adding another class with your desired style, and using state to track the squares that have been clicked.
const [boardIndeces, setBoardIndeces] = useState(initArray(board));
const initArray = arr => {
let rows = [];
for (let i = 0; i < arr.length; i++) {
let row = [];
const currBoard = arr[i];
for (let z = 0; z < currBoard.length; z++) {
row[z] = false;
}
rows[i] = row;
}
return rows;
};
const onCellClick = (rowIdx, cellIdx) => {
if (!(boardIndeces[rowIdx] && boardIndeces[rowIdx][cellIdx])) {
boardIndeces[rowIdx][cellIdx] = true;
setBoardIndeces([...boardIndeces]);
}
};
{
board.map((row, rowIdx) => (
<div key={rowIdx}>
{row.map((cell, cellIdx) => (
<div
key={cellIdx}
className={
boardIndeces[rowIdx].includes(cellIdx)
? 'your_active_class'
: 'your_inactive_class'
}
onClick={() => onCellClick(rowIdx, cellIdx)}
></div>
))}
</div>
));
}
You can use a checkbox if you don't want to use React
HTML
<input type="checkbox" id="color" name="color">
<label id="color-div" for="color">
<!-- the div you want to change color -->
</label>
CSS
#color {
display: none
}
#color:checked + #color-div { /* + in CSS is the sibling combinator */
background-color: #fffff /* your background color */
}
What you're basically doing is making an invisible checkbox and toggling it with the label, when it's toggled you do the changes to the CSS
Remember the CSS combinators only work in elements after the HTML element it's being applied to

Can I add alpha transparency to a CSS color variable? [duplicate]

I am designing an app in electron, so I have access to CSS variables. I have defined a color variable in vars.css:
:root {
--color: #f0f0f0;
}
I want to use this color in main.css, but with some opacity applied:
#element {
background: (somehow use var(--color) at some opacity);
}
How would I go about doing this? I am not using any preprocessor, only CSS. I would prefer an all-CSS answer, but I will accept JavaScript/jQuery.
I cannot use opacity because I am using a background image that should not be transparent.
You can't take an existing color value and apply an alpha channel to it. Namely, you can't take an existing hex value such as #f0f0f0, give it an alpha component and use the resulting value with another property.
However, custom properties allow you to convert your hex value into an RGB triplet for use with rgba(), store that value in the custom property (including the commas!), substitute that value using var() into an rgba() function with your desired alpha value, and it'll just work:
:root {
/* #f0f0f0 in decimal RGB */
--color: 240, 240, 240;
}
body {
color: #000;
background-color: #000;
}
#element {
background-color: rgba(var(--color), 0.8);
}
<p id="element">If you can see this, your browser supports custom properties.</p>
This seems almost too good to be true.1 How does it work?
The magic lies in the fact that the values of custom properties are substituted as is when replacing var() references in a property value, before that property's value is computed. This means that as far as custom properties are concerned, the value of --color in your example isn't a color value at all until a var(--color) expression appears somewhere that expects a color value (and only in that context). From section 2.1 of the css-variables spec:
The allowed syntax for custom properties is extremely permissive. The <declaration-value> production matches any sequence of one or more tokens, so long as the sequence does not contain <bad-string-token>, <bad-url-token>, unmatched <)-token>, <]-token>, or <}-token>, or top-level <semicolon-token> tokens or <delim-token> tokens with a value of "!".
For example, the following is a valid custom property:
--foo: if(x > 5) this.width = 10;
While this value is obviously useless as a variable, as it would be invalid in any normal property, it might be read and acted on by JavaScript.
And section 3:
If a property contains one or more var() functions, and those functions are syntactically valid, the entire property’s grammar must be assumed to be valid at parse time. It is only syntax-checked at computed-value time, after var() functions have been substituted.
This means that the 240, 240, 240 value you see above gets substituted directly into the rgba() function before the declaration is computed. So this:
#element {
background-color: rgba(var(--color), 0.8);
}
which doesn't appear to be valid CSS at first because rgba() expects no less than four comma-separated numeric values, becomes this:
#element {
background-color: rgba(240, 240, 240, 0.8);
}
which, of course, is perfectly valid CSS.
Taking it one step further, you can store the alpha component in its own custom property:
:root {
--color: 240, 240, 240;
--alpha: 0.8;
}
and substitute it, with the same result:
#element {
background-color: rgba(var(--color), var(--alpha));
}
This allows you to have different alpha values that you can swap around on-the-fly.
1 Well, it is, if you're running the code snippet in a browser that doesn't support custom properties.
Relative color syntax
With this new CSS ability (css-color-5) which allows color format transformations, it also will also allow adding opacity to any color in any format, for example, to RGB (relative transformations can be done to any other format):
html { --color: blue }
.with-opacity { background: rgb(from var(--color) r g b / 50%) }
(As of writing, not yet available in browsers. Will update once arrives)
👉 Codepen demo
I know the OP isn't using a preprocessor, but I would have been helped if the following information was part of the answer here (I can't comment yet, otherwise I would have commented #BoltClock answer.
If you are using, e.g. scss, the answer above will fail, because scss attempts to compile the styles with a scss-specific rgba()/hsla() function, which requires 4 parameters. However, rgba()/hsla() are also native css functions, so you can use string interpolation to bypass the scss function.
Example (valid in sass 3.5.0+):
:root {
--color_rgb: 250, 250, 250;
--color_hsl: 250, 50%, 50%;
}
div {
/* This is valid CSS, but will fail in a scss compilation */
background-color: rgba(var(--color_rgb), 0.5);
/* This is valid scss, and will generate the CSS above */
background-color: #{'rgba(var(--color_rgb), 0.5)'};
}
<div></div>
Note that string interpolation will not work for non-CSS scss functions, such as lighten(), because the resulting code would not be functional CSS. It would still be valid scss though, so you would receive no error in compilation.
I was in a similar situation, but unfortunately the given solutions did not work for me, as the variables could be anything from rgb to hsl to hex or even color names.
I solved this issue now, by applying the background-color and the opacity to a pseudo :after or :before element:
.container {
position: relative;
}
.container::before {
content: "";
width: 100%;
height: 100%;
position: absolute;
left: 0;
background-color: var(--color);
opacity: 0.3;
}
The styles might need to be changed a little, depending on the element the background should be applied to.
Also it might not work for all situations, but hopefully it helps in some cases, where the other solutions can't be used.
Edit:
I just noticed, that this solution obviously also impacts the text color, as it creates an element in front of the target element and applies a transparent background color to it.
This might be a problem in some cases.
you can use linear-gradient to hack the color:
background: linear-gradient(to bottom, var(--your-color) -1000%, var(--mixin-color), 1000%)
$(() => {
const setOpacity = () => {
$('#canvas').css('--opacity', $('#opacity-value').val())
}
const setColor = () => {
$('#canvas').css('--color', $('#color-value').val());
}
$('#opacity-value').on('input', setOpacity);
$('#color-value').on('input', setColor);
setOpacity();
setColor();
})
#canvas {
width: 100px;
height: 100px;
border: 2px solid #000;
--hack: 10000%;
background: linear-gradient( to bottom, var(--color) calc((var(--opacity) - 1) * var(--hack)), transparent calc(var(--opacity) * var(--hack)));
}
#container {
background-image: linear-gradient(45deg, #b0b0b0 25%, transparent 25%), linear-gradient(-45deg, #b0b0b0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b0b0b0 75%), linear-gradient(-45deg, transparent 75%, #b0b0b0 75%);
background-size: 20px 20px;
background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
padding: 10px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="canvas"></div>
</div>
<hr/>
<input type="range" id="opacity-value" min="0" max="1" step="0.1" value="0.5" />
<input type="color" id="color-value" />
If you use dark and light mode, i use this sample. I prefer separate between colors and rgb colors variable assignment. So i use two each loop. I realise this solution is not dry code. If you want to dry code could you use one loop.
$colors-light: (
white: #fff,
black: #0c0d0e,
orange: #f48024,
green: #5eba7d,
blue: #0077cc,
red: #d1383d,
red-100: #e2474c,
red-200: red,
);
$colors-dark: (
black: #fff,
white: #2d2d2d,
orange: #dd7118,
green: #5eba7d,
blue: #0077cc,
red: #aa1c21,
red-100: #c9292e,
red-200: red,
);
#function hexToRGB($hex) {
#return red($hex), green($hex), blue($hex);
}
#mixin generate_colors($colors) {
// Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--#{$color}: #{$value};
} #else {
--#{$color}: var(--#{$value});
}
}
// RGB Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--RGB_#{$color}: #{hexToRGB($value)};
} #else {
--RGB_#{$color}: var(--RGB_#{$value});
}
}
}
:root {
#include generate_colors($colors-light);
}
[data-theme="dark"] {
#include generate_colors($colors-dark);
}
dry code
#mixin generate_colors($colors) {
// Colors, RGB Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--#{$color}: #{$value};
--RGB_#{$color}: #{hexToRGB($value)};
} #else {
--#{$color}: var(--#{$value});
--RGB_#{$color}: var(--RGB_#{$value});
}
}
}
css Output
:root {
--white: #fff;
--RGB_white: 255, 255, 255;
--black: #0c0d0e;
--RGB_black: 12, 13, 14;
--orange: #f48024;
--RGB_orange: 244, 128, 36;
--green: #5eba7d;
--RGB_green: 94, 186, 125;
--blue: #0077cc;
--RGB_blue: 0, 119, 204;
--red: #d1383d;
--RGB_red: 209, 56, 61;
--red-100: #e2474c;
--RGB_red-100: 226, 71, 76;
--red-200: var(--red);
--RGB_red-200: var(--RGB_red);
}
[data-theme="dark"] {
--black: #fff;
--RGB_black: 255, 255, 255;
--white: #2d2d2d;
--RGB_white: 45, 45, 45;
--orange: #dd7118;
--RGB_orange: 221, 113, 24;
--green: #5eba7d;
--RGB_green: 94, 186, 125;
--blue: #0077cc;
--RGB_blue: 0, 119, 204;
--red: #aa1c21;
--RGB_red: 170, 28, 33;
--red-100: #c9292e;
--RGB_red-100: 201, 41, 46;
--red-200: var(--red);
--RGB_red-200: var(--RGB_red);
}
body {
background-color: var(--white);
}
.colors {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin: 50px 0 0 30px;
}
.box {
width: 100px;
height: 100px;
margin-right: 5px;
}
.black {
background-color: var(--black);
}
.white {
background-color: var(--white);
}
.orange {
background-color: var(--orange);
}
.green {
background-color: var(--green);
}
.blue {
background-color: var(--blue);
}
.red {
background-color: var(--red);
}
.red-200 {
background-color: var(--red-200);
}
.black-rgba {
background-color: rgba(var(--RGB_black), 0.5);
}
.white-rgba {
background-color: rgba(var(--RGB_white), 0.5);
}
.orange-rgba {
background-color: rgba(var(--RGB_orange), 0.5);
}
.green-rgba {
background-color: rgba(var(--RGB_green), 0.5);
}
.blue-rgba {
background-color: rgba(var(--RGB_blue), 0.5);
}
.red-rgba {
background-color: rgba(var(--RGB_red), 0.5);
}
.red-rgba-200 {
background-color: rgba(var(--RGB_red-200), 0.5);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<input type="checkbox" id="dark-switch" name="theme" />
<label for="dark-switch">Dark / Light</label>
</div>
<div class="color-box">
<div class="colors">
<div class="box red-200"></div>
<div class="box black"></div>
<div class="box white"></div>
<div class="box orange"></div>
<div class="box green"></div>
<div class="box blue"></div>
<div class="box red"></div>
</div>
<br>
<h1>RGBA</h1>
<div class="colors">
<div class="box red-rgba-200"></div>
<div class="box black-rgba"></div>
<div class="box white-rgba"></div>
<div class="box orange-rgba"></div>
<div class="box green-rgba"></div>
<div class="box blue-rgba"></div>
<div class="box red-rgba"></div>
</div>
</div>
<script>
const dark_switch = document.getElementById("dark-switch");
dark_switch.addEventListener("change", (e) => {
e.target.checked
? document.documentElement.setAttribute("data-theme", "dark")
: document.documentElement.setAttribute("data-theme", "light");
});
</script>
</body>
</html>
This is indeed possible with CSS. It's just a bit dirty, and you'll have to use gradients. I've coded a small snippet as example, take note that for dark backgrounds, you should use the black opacity, as for light- the white ones.:
:root {
--red: rgba(255, 0, 0, 1);
--white-low-opacity: rgba(255, 255, 255, .3);
--white-high-opacity: rgba(255, 255, 255, .7);
--black-low-opacity: rgba(0, 0, 0, .3);
--black-high-opacity: rgba(0, 0, 0, .7);
}
div {
width: 100px;
height: 100px;
margin: 10px;
}
.element1 {
background:
linear-gradient(var(--white-low-opacity), var(--white-low-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element2 {
background:
linear-gradient(var(--white-high-opacity), var(--white-high-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element3 {
background:
linear-gradient(var(--black-low-opacity), var(--black-low-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element4 {
background:
linear-gradient(var(--black-high-opacity), var(--black-high-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
<div class="element1">hello world</div>
<div class="element2">hello world</div>
<div class="element3">hello world</div>
<div class="element4">hello world</div>
SCSS / SASS
Advantage: You can just use Hex color values, instead to use the 8 Bit for every channel (0-255).
This is how I did it with the initial idea of: https://codyhouse.co/blog/post/how-to-combine-sass-color-functions-and-css-variables
Edit: You could also modify the alpha function to just use #{$color-name}-rgb and omit the generated *-r, *-g, *-b CSS variables.
Result
body {
--main-color: rgb(170, 68, 204);
--main-color-rgb: 170,68,204;
--main-color-r: 170;
--main-color-g: 68;
--main-color-b: 204;
}
.button-test {
// Generated from the alpha function
color: rgba(var(--main-color-r), var(--main-color-g), var(--main-color-b), 0.5);
// OR (you wrote this yourself, see usage)
color: rgba(var(--main-color-rgb), 0.5);
}
Usage:
body {
#include defineColorRGB(--main-color, #aa44cc);
}
.button-test {
// With alpha function:
color: alpha(var(--main-color), 0.5);
// OR just using the generated variable directly
color: rgba(var(--main-color-rgb), 0.5);
}
Mixin and functions
#mixin defineColorRGB($color-name, $value) {
$red: red($value);
$green: green($value);
$blue: blue($value);
#{$color-name}: unquote("rgb(#{$red}, #{$green}, #{$blue})");
#{$color-name}-rgb: $red,$green,$blue;
#{$color-name}-r: $red;
#{$color-name}-g: $green;
#{$color-name}-b: $blue;
}
// replace substring with another string
// credits: https://css-tricks.com/snippets/sass/str-replace-function/
#function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
#if $index {
#return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
#return $string;
}
#function alpha($color, $opacity) {
$color: str-replace($color, 'var(');
$color: str-replace($color, ')');
$color-r: var(#{$color+'-r'});
$color-g: var(#{$color+'-g'});
$color-b: var(#{$color+'-b'});
#return rgba($color-r, $color-g, $color-b, $opacity);
}
You can set specific variable/value for each color - the original and the one with opacity:
:root {
--color: #F00;
--color-opacity: rgba(255, 0, 0, 0.5);
}
#a1 {
background: var(--color);
}
#a2 {
background: var(--color-opacity);
}
<div id="a1">asdf</div>
<div id="a2">asdf</div>
If you can't use this and you are ok with javascript solution, you can use this one:
$(function() {
$('button').click(function() {
bgcolor = $('#a2').css('backgroundColor');
rgb_value = bgcolor.match(/\d+,\s?\d+,\s?\d+/)[0]
$('#a2').css('backgroundColor', 'rgba(' + rgb_value + ', 0.5)');
});
});
:root {
--color: #F00;
}
#a1 {
background: var(--color);
}
#a2 {
background: var(--color);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1">asdf</div>
<div id="a2">asdf</div>
<button>Click to change opacity</button>
:root{
--color: 255, 0, 0;
}
#element{
background-color: rgba(var(--color), opacity);
}
where you replace opacity with anything between 0 and 1
First time posting here..
A simple JavaScript solution
Here's a simple JavaScript function that can add transparency to named color CSS colors like 'red'
Although .setFillColor() is depreciated it is still implemented in some browsers (blink & webkit). If setFillColor() ever gets dropped completely hopefully we'll have Relative color syntax by then.
function addTransparency(color, alpha) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.setFillColor(color, alpha);
return ctx.fillStyle;
}
Usage with CSS variables
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Transparency to a Color</title>
<style>
:root {
--color: lime;
--alpha: 0.5;
}
.test {
background-color: var(--color);
}
</style>
</head>
<body class='test'>
<script>
try{"use strict"
/* Use the getComputedStyle() method to get the current value of the CSS variable --color and the --alpha variable. */
const color = getComputedStyle(document.documentElement).getPropertyValue('--color')||'white'; //added fallback to color white
const alpha = getComputedStyle(document.documentElement).getPropertyValue('--alpha')||1; //added fallback to solid color value of 1
/* Call the addTransparency() function with the color and alpha values as arguments, and store the result in a variable. */
const transparentColor = addTransparency(color, alpha);
/* Use the setProperty() method of the CSSStyleDeclaration interface to set the value of the --color CSS variable to the value of the transparentColor variable. */
document.documentElement.style.setProperty('--color', transparentColor);
function addTransparency(color, alpha) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.setFillColor(color, alpha);
return ctx.fillStyle;
}
}catch(e){document.write(e);}
</script>
</body>
</html>
Ah page refreshed and I lost everything I typed, posting the draft that saved.
If you love hex colors like me there is another solution.
The hex value is 6 digits after that is the alpha value.
00 is 100% transparency 99 is about 75% then it uses the alphabet 'a1-af' then 'b1-bf' ending with 'ff' which is 100% opaque.
:root {
--color: #F00;
}
#element {
background: var(--color)f6;
}
For using rgba() with general css variable, try this:
Declare your color inside :root, but don't use rgb() as other answers do. just write the value
:root{
--color : 255,0,0;
}
Use --color variable using var() as other answers
#some-element {
color : rgba(var(--color),0.5);
}
In CSS you should be able to either use rgba values:
#element {
background: rgba(240, 240, 240, 0.5);
}
or just set the opacity:
#element {
background: #f0f0f0;
opacity: 0.5;
}

How do I apply opacity to a CSS color variable?

I am designing an app in electron, so I have access to CSS variables. I have defined a color variable in vars.css:
:root {
--color: #f0f0f0;
}
I want to use this color in main.css, but with some opacity applied:
#element {
background: (somehow use var(--color) at some opacity);
}
How would I go about doing this? I am not using any preprocessor, only CSS. I would prefer an all-CSS answer, but I will accept JavaScript/jQuery.
I cannot use opacity because I am using a background image that should not be transparent.
You can't take an existing color value and apply an alpha channel to it. Namely, you can't take an existing hex value such as #f0f0f0, give it an alpha component and use the resulting value with another property.
However, custom properties allow you to convert your hex value into an RGB triplet for use with rgba(), store that value in the custom property (including the commas!), substitute that value using var() into an rgba() function with your desired alpha value, and it'll just work:
:root {
/* #f0f0f0 in decimal RGB */
--color: 240, 240, 240;
}
body {
color: #000;
background-color: #000;
}
#element {
background-color: rgba(var(--color), 0.8);
}
<p id="element">If you can see this, your browser supports custom properties.</p>
This seems almost too good to be true.1 How does it work?
The magic lies in the fact that the values of custom properties are substituted as is when replacing var() references in a property value, before that property's value is computed. This means that as far as custom properties are concerned, the value of --color in your example isn't a color value at all until a var(--color) expression appears somewhere that expects a color value (and only in that context). From section 2.1 of the css-variables spec:
The allowed syntax for custom properties is extremely permissive. The <declaration-value> production matches any sequence of one or more tokens, so long as the sequence does not contain <bad-string-token>, <bad-url-token>, unmatched <)-token>, <]-token>, or <}-token>, or top-level <semicolon-token> tokens or <delim-token> tokens with a value of "!".
For example, the following is a valid custom property:
--foo: if(x > 5) this.width = 10;
While this value is obviously useless as a variable, as it would be invalid in any normal property, it might be read and acted on by JavaScript.
And section 3:
If a property contains one or more var() functions, and those functions are syntactically valid, the entire property’s grammar must be assumed to be valid at parse time. It is only syntax-checked at computed-value time, after var() functions have been substituted.
This means that the 240, 240, 240 value you see above gets substituted directly into the rgba() function before the declaration is computed. So this:
#element {
background-color: rgba(var(--color), 0.8);
}
which doesn't appear to be valid CSS at first because rgba() expects no less than four comma-separated numeric values, becomes this:
#element {
background-color: rgba(240, 240, 240, 0.8);
}
which, of course, is perfectly valid CSS.
Taking it one step further, you can store the alpha component in its own custom property:
:root {
--color: 240, 240, 240;
--alpha: 0.8;
}
and substitute it, with the same result:
#element {
background-color: rgba(var(--color), var(--alpha));
}
This allows you to have different alpha values that you can swap around on-the-fly.
1 Well, it is, if you're running the code snippet in a browser that doesn't support custom properties.
Relative color syntax
With this new CSS ability (css-color-5) which allows color format transformations, it also will also allow adding opacity to any color in any format, for example, to RGB (relative transformations can be done to any other format):
html { --color: blue }
.with-opacity { background: rgb(from var(--color) r g b / 50%) }
(As of writing, not yet available in browsers. Will update once arrives)
👉 Codepen demo
I know the OP isn't using a preprocessor, but I would have been helped if the following information was part of the answer here (I can't comment yet, otherwise I would have commented #BoltClock answer.
If you are using, e.g. scss, the answer above will fail, because scss attempts to compile the styles with a scss-specific rgba()/hsla() function, which requires 4 parameters. However, rgba()/hsla() are also native css functions, so you can use string interpolation to bypass the scss function.
Example (valid in sass 3.5.0+):
:root {
--color_rgb: 250, 250, 250;
--color_hsl: 250, 50%, 50%;
}
div {
/* This is valid CSS, but will fail in a scss compilation */
background-color: rgba(var(--color_rgb), 0.5);
/* This is valid scss, and will generate the CSS above */
background-color: #{'rgba(var(--color_rgb), 0.5)'};
}
<div></div>
Note that string interpolation will not work for non-CSS scss functions, such as lighten(), because the resulting code would not be functional CSS. It would still be valid scss though, so you would receive no error in compilation.
I was in a similar situation, but unfortunately the given solutions did not work for me, as the variables could be anything from rgb to hsl to hex or even color names.
I solved this issue now, by applying the background-color and the opacity to a pseudo :after or :before element:
.container {
position: relative;
}
.container::before {
content: "";
width: 100%;
height: 100%;
position: absolute;
left: 0;
background-color: var(--color);
opacity: 0.3;
}
The styles might need to be changed a little, depending on the element the background should be applied to.
Also it might not work for all situations, but hopefully it helps in some cases, where the other solutions can't be used.
Edit:
I just noticed, that this solution obviously also impacts the text color, as it creates an element in front of the target element and applies a transparent background color to it.
This might be a problem in some cases.
you can use linear-gradient to hack the color:
background: linear-gradient(to bottom, var(--your-color) -1000%, var(--mixin-color), 1000%)
$(() => {
const setOpacity = () => {
$('#canvas').css('--opacity', $('#opacity-value').val())
}
const setColor = () => {
$('#canvas').css('--color', $('#color-value').val());
}
$('#opacity-value').on('input', setOpacity);
$('#color-value').on('input', setColor);
setOpacity();
setColor();
})
#canvas {
width: 100px;
height: 100px;
border: 2px solid #000;
--hack: 10000%;
background: linear-gradient( to bottom, var(--color) calc((var(--opacity) - 1) * var(--hack)), transparent calc(var(--opacity) * var(--hack)));
}
#container {
background-image: linear-gradient(45deg, #b0b0b0 25%, transparent 25%), linear-gradient(-45deg, #b0b0b0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b0b0b0 75%), linear-gradient(-45deg, transparent 75%, #b0b0b0 75%);
background-size: 20px 20px;
background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
padding: 10px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="canvas"></div>
</div>
<hr/>
<input type="range" id="opacity-value" min="0" max="1" step="0.1" value="0.5" />
<input type="color" id="color-value" />
If you use dark and light mode, i use this sample. I prefer separate between colors and rgb colors variable assignment. So i use two each loop. I realise this solution is not dry code. If you want to dry code could you use one loop.
$colors-light: (
white: #fff,
black: #0c0d0e,
orange: #f48024,
green: #5eba7d,
blue: #0077cc,
red: #d1383d,
red-100: #e2474c,
red-200: red,
);
$colors-dark: (
black: #fff,
white: #2d2d2d,
orange: #dd7118,
green: #5eba7d,
blue: #0077cc,
red: #aa1c21,
red-100: #c9292e,
red-200: red,
);
#function hexToRGB($hex) {
#return red($hex), green($hex), blue($hex);
}
#mixin generate_colors($colors) {
// Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--#{$color}: #{$value};
} #else {
--#{$color}: var(--#{$value});
}
}
// RGB Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--RGB_#{$color}: #{hexToRGB($value)};
} #else {
--RGB_#{$color}: var(--RGB_#{$value});
}
}
}
:root {
#include generate_colors($colors-light);
}
[data-theme="dark"] {
#include generate_colors($colors-dark);
}
dry code
#mixin generate_colors($colors) {
// Colors, RGB Colors
#each $color, $value in $colors {
#if str-slice(#{$value}, 1, 1) == "#" {
--#{$color}: #{$value};
--RGB_#{$color}: #{hexToRGB($value)};
} #else {
--#{$color}: var(--#{$value});
--RGB_#{$color}: var(--RGB_#{$value});
}
}
}
css Output
:root {
--white: #fff;
--RGB_white: 255, 255, 255;
--black: #0c0d0e;
--RGB_black: 12, 13, 14;
--orange: #f48024;
--RGB_orange: 244, 128, 36;
--green: #5eba7d;
--RGB_green: 94, 186, 125;
--blue: #0077cc;
--RGB_blue: 0, 119, 204;
--red: #d1383d;
--RGB_red: 209, 56, 61;
--red-100: #e2474c;
--RGB_red-100: 226, 71, 76;
--red-200: var(--red);
--RGB_red-200: var(--RGB_red);
}
[data-theme="dark"] {
--black: #fff;
--RGB_black: 255, 255, 255;
--white: #2d2d2d;
--RGB_white: 45, 45, 45;
--orange: #dd7118;
--RGB_orange: 221, 113, 24;
--green: #5eba7d;
--RGB_green: 94, 186, 125;
--blue: #0077cc;
--RGB_blue: 0, 119, 204;
--red: #aa1c21;
--RGB_red: 170, 28, 33;
--red-100: #c9292e;
--RGB_red-100: 201, 41, 46;
--red-200: var(--red);
--RGB_red-200: var(--RGB_red);
}
body {
background-color: var(--white);
}
.colors {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin: 50px 0 0 30px;
}
.box {
width: 100px;
height: 100px;
margin-right: 5px;
}
.black {
background-color: var(--black);
}
.white {
background-color: var(--white);
}
.orange {
background-color: var(--orange);
}
.green {
background-color: var(--green);
}
.blue {
background-color: var(--blue);
}
.red {
background-color: var(--red);
}
.red-200 {
background-color: var(--red-200);
}
.black-rgba {
background-color: rgba(var(--RGB_black), 0.5);
}
.white-rgba {
background-color: rgba(var(--RGB_white), 0.5);
}
.orange-rgba {
background-color: rgba(var(--RGB_orange), 0.5);
}
.green-rgba {
background-color: rgba(var(--RGB_green), 0.5);
}
.blue-rgba {
background-color: rgba(var(--RGB_blue), 0.5);
}
.red-rgba {
background-color: rgba(var(--RGB_red), 0.5);
}
.red-rgba-200 {
background-color: rgba(var(--RGB_red-200), 0.5);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<input type="checkbox" id="dark-switch" name="theme" />
<label for="dark-switch">Dark / Light</label>
</div>
<div class="color-box">
<div class="colors">
<div class="box red-200"></div>
<div class="box black"></div>
<div class="box white"></div>
<div class="box orange"></div>
<div class="box green"></div>
<div class="box blue"></div>
<div class="box red"></div>
</div>
<br>
<h1>RGBA</h1>
<div class="colors">
<div class="box red-rgba-200"></div>
<div class="box black-rgba"></div>
<div class="box white-rgba"></div>
<div class="box orange-rgba"></div>
<div class="box green-rgba"></div>
<div class="box blue-rgba"></div>
<div class="box red-rgba"></div>
</div>
</div>
<script>
const dark_switch = document.getElementById("dark-switch");
dark_switch.addEventListener("change", (e) => {
e.target.checked
? document.documentElement.setAttribute("data-theme", "dark")
: document.documentElement.setAttribute("data-theme", "light");
});
</script>
</body>
</html>
This is indeed possible with CSS. It's just a bit dirty, and you'll have to use gradients. I've coded a small snippet as example, take note that for dark backgrounds, you should use the black opacity, as for light- the white ones.:
:root {
--red: rgba(255, 0, 0, 1);
--white-low-opacity: rgba(255, 255, 255, .3);
--white-high-opacity: rgba(255, 255, 255, .7);
--black-low-opacity: rgba(0, 0, 0, .3);
--black-high-opacity: rgba(0, 0, 0, .7);
}
div {
width: 100px;
height: 100px;
margin: 10px;
}
.element1 {
background:
linear-gradient(var(--white-low-opacity), var(--white-low-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element2 {
background:
linear-gradient(var(--white-high-opacity), var(--white-high-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element3 {
background:
linear-gradient(var(--black-low-opacity), var(--black-low-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
.element4 {
background:
linear-gradient(var(--black-high-opacity), var(--black-high-opacity)) no-repeat,
linear-gradient(var(--red), var(--red)) no-repeat;
}
<div class="element1">hello world</div>
<div class="element2">hello world</div>
<div class="element3">hello world</div>
<div class="element4">hello world</div>
SCSS / SASS
Advantage: You can just use Hex color values, instead to use the 8 Bit for every channel (0-255).
This is how I did it with the initial idea of: https://codyhouse.co/blog/post/how-to-combine-sass-color-functions-and-css-variables
Edit: You could also modify the alpha function to just use #{$color-name}-rgb and omit the generated *-r, *-g, *-b CSS variables.
Result
body {
--main-color: rgb(170, 68, 204);
--main-color-rgb: 170,68,204;
--main-color-r: 170;
--main-color-g: 68;
--main-color-b: 204;
}
.button-test {
// Generated from the alpha function
color: rgba(var(--main-color-r), var(--main-color-g), var(--main-color-b), 0.5);
// OR (you wrote this yourself, see usage)
color: rgba(var(--main-color-rgb), 0.5);
}
Usage:
body {
#include defineColorRGB(--main-color, #aa44cc);
}
.button-test {
// With alpha function:
color: alpha(var(--main-color), 0.5);
// OR just using the generated variable directly
color: rgba(var(--main-color-rgb), 0.5);
}
Mixin and functions
#mixin defineColorRGB($color-name, $value) {
$red: red($value);
$green: green($value);
$blue: blue($value);
#{$color-name}: unquote("rgb(#{$red}, #{$green}, #{$blue})");
#{$color-name}-rgb: $red,$green,$blue;
#{$color-name}-r: $red;
#{$color-name}-g: $green;
#{$color-name}-b: $blue;
}
// replace substring with another string
// credits: https://css-tricks.com/snippets/sass/str-replace-function/
#function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
#if $index {
#return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
#return $string;
}
#function alpha($color, $opacity) {
$color: str-replace($color, 'var(');
$color: str-replace($color, ')');
$color-r: var(#{$color+'-r'});
$color-g: var(#{$color+'-g'});
$color-b: var(#{$color+'-b'});
#return rgba($color-r, $color-g, $color-b, $opacity);
}
You can set specific variable/value for each color - the original and the one with opacity:
:root {
--color: #F00;
--color-opacity: rgba(255, 0, 0, 0.5);
}
#a1 {
background: var(--color);
}
#a2 {
background: var(--color-opacity);
}
<div id="a1">asdf</div>
<div id="a2">asdf</div>
If you can't use this and you are ok with javascript solution, you can use this one:
$(function() {
$('button').click(function() {
bgcolor = $('#a2').css('backgroundColor');
rgb_value = bgcolor.match(/\d+,\s?\d+,\s?\d+/)[0]
$('#a2').css('backgroundColor', 'rgba(' + rgb_value + ', 0.5)');
});
});
:root {
--color: #F00;
}
#a1 {
background: var(--color);
}
#a2 {
background: var(--color);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1">asdf</div>
<div id="a2">asdf</div>
<button>Click to change opacity</button>
:root{
--color: 255, 0, 0;
}
#element{
background-color: rgba(var(--color), opacity);
}
where you replace opacity with anything between 0 and 1
First time posting here..
A simple JavaScript solution
Here's a simple JavaScript function that can add transparency to named color CSS colors like 'red'
Although .setFillColor() is depreciated it is still implemented in some browsers (blink & webkit). If setFillColor() ever gets dropped completely hopefully we'll have Relative color syntax by then.
function addTransparency(color, alpha) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.setFillColor(color, alpha);
return ctx.fillStyle;
}
Usage with CSS variables
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Transparency to a Color</title>
<style>
:root {
--color: lime;
--alpha: 0.5;
}
.test {
background-color: var(--color);
}
</style>
</head>
<body class='test'>
<script>
try{"use strict"
/* Use the getComputedStyle() method to get the current value of the CSS variable --color and the --alpha variable. */
const color = getComputedStyle(document.documentElement).getPropertyValue('--color')||'white'; //added fallback to color white
const alpha = getComputedStyle(document.documentElement).getPropertyValue('--alpha')||1; //added fallback to solid color value of 1
/* Call the addTransparency() function with the color and alpha values as arguments, and store the result in a variable. */
const transparentColor = addTransparency(color, alpha);
/* Use the setProperty() method of the CSSStyleDeclaration interface to set the value of the --color CSS variable to the value of the transparentColor variable. */
document.documentElement.style.setProperty('--color', transparentColor);
function addTransparency(color, alpha) {
const ctx = document.createElement('canvas').getContext('2d');
ctx.setFillColor(color, alpha);
return ctx.fillStyle;
}
}catch(e){document.write(e);}
</script>
</body>
</html>
Ah page refreshed and I lost everything I typed, posting the draft that saved.
If you love hex colors like me there is another solution.
The hex value is 6 digits after that is the alpha value.
00 is 100% transparency 99 is about 75% then it uses the alphabet 'a1-af' then 'b1-bf' ending with 'ff' which is 100% opaque.
:root {
--color: #F00;
}
#element {
background: var(--color)f6;
}
For using rgba() with general css variable, try this:
Declare your color inside :root, but don't use rgb() as other answers do. just write the value
:root{
--color : 255,0,0;
}
Use --color variable using var() as other answers
#some-element {
color : rgba(var(--color),0.5);
}
In CSS you should be able to either use rgba values:
#element {
background: rgba(240, 240, 240, 0.5);
}
or just set the opacity:
#element {
background: #f0f0f0;
opacity: 0.5;
}

Resources