Home > other >  How to make a solid variable background color lower its opacity
How to make a solid variable background color lower its opacity

Time:06-26

For example I have a variable named dark1 with value of #242424.
Now I want to change the opacity of the variable (or the background) without changing the value of it.

EXAMPLE:

:root {
  --dark: #242424;
}

p {
  padding: 40px;
  color: var(--dark);
}

div {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  background: var(--dark); // <- opacity should be like 0.8 or something 
  // the content below the element should be slightly visible and with blur
  // the background should be lighter but while only using the "dark" variable
  
  backdrop-filter: blur(10px);
}
<p>Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text</p>

<!-- The main idea is to blur the content below the backdrop element -->
<div ></div>

CodePudding user response:

It is not possible at the moment. With the upcoming color-5 draft from W3C, it will be. At the moment, however, it is not supported by a single browser.

I assume you don't want to change the variable because you have other places where the color applies. But I have a workaround solution for you here:

Create a new CSS variable like --dark-base. Then convert your HEX value to a RGB value which would be: #242424 => RGB(36, 36, 36)

As such define your base variable as: --dark-base: 36, 36, 36;
Next you change your existing HEX color to RGB: `--dark: rgb(var(--dark-base));

Nothing on your site will change by changing this CSS part. As said, the color will be the same no matter where you already used the variable. It now is just an RGB instead of a HEX color.

Last but not least to solve your problem to add opacity: rgba(var(--dark), 0.8) will work now:

:root {
  --dark-base: 36, 36, 36;
  --dark: rgb(var(--dark-base));
}

p {
  padding: 40px;
  color: var(--dark);
}

div {
  position: fixed;
  inset: 0;
  background: rgba(var(--dark-base), 0.8); 
  backdrop-filter: blur(10px);
}
<p>Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text, Just some dummy text</p>

<!-- The main idea is to blur the content below the backdrop element -->
<div ></div>

CodePudding user response:

You need to convert the HEX-code into an rgba-code.

Use something like rgbacolorpicker.

The fourth value is the opacity, which you can set to whatever value you'd like: rgba(36, 36, 36, 1)

  • Related