3

Say I have a CSS variable for an hsl defined as such:

--white-1: hsl(0deg 0% 100%); 

Now, I want to use that same white, but at 50% opacity. So, something like this:

--white-2: hsla(0deg 0% 100% 50%);

Is there a way to use the first variable --white-1 in the definition of the variable --white-2? I guess I want to do something like this:

--white-2: hsla(var(--white-1) 50%);

Is there a way to achieve this in CSS?

1
  • it should be noted that hsla() will become obsolete. hsl() accept a fourth argument for the opacity hsl(0deg 0% 100% / 50%) Commented Nov 17, 2021 at 13:51

2 Answers 2

8

You can do it using Relative Colors:

:root {
    --white-1: hsl(0deg 0% 100%);
    --white-2: hsl(from var(--white-1) h s l / 50%);  
}
Sign up to request clarification or add additional context in comments.

Comments

2

I would solve it like that

:root {
    --white-1: 0deg, 0%, 100%;
    --white-2: var(--white-1), 0.5; 
}

.wrapper{
  background: linear-gradient(90deg, rgba(155,194,89,1) 0%, rgba(194,166,89,1) 15%, rgba(89,179,194,1) 50%, rgba(155,194,89,1) 85%, rgba(194,89,183,1) 100%);
  padding: 3rem;
}

.div-1 {
    background: hsl(var(--white-1));
    width: 100px;
    height: 100px;
    margin: 1rem;
}

.div-2 {
    background: hsla(var(--white-2));
    width: 100px;
    height: 100px;
    margin: 1rem;
}
<div class="wrapper">
  <div class="div-1">--white-1</div>
  <div class="div-2">--white-2</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.