0

Is there a way to set the value of a property for a CSS class dynamically, without using a compiler or javascript.

:root {
--color-0 : red;
--color-1 : blue;
--color-3 : yellow;
}

.bg-color-[*] {
    background-color: var(--color-[*]);
}

Then in my html I could pass in the numeric value that is used to select the correct variable

<div class="bg-color-1">This background should be red</div>
<div class="bg-color-2">This background should be blue</div>
<div class="bg-color-3">This background should be yellow</div>
3
  • 4
    no, you cannot .. Commented Oct 20, 2022 at 12:28
  • @TemaniAfif that is unfortunate. Thank you. Commented Oct 20, 2022 at 12:30
  • CSS variables only work for values. In your case, you need to set variables for the names (not only values) and on top of that an iteration method to loop through a range or array. That's why preprocessors such as SASS and LESS were developed. Commented Oct 20, 2022 at 12:35

2 Answers 2

1

Unfortunately this is not possible in CSS. CSS itself doesn't really have the ability to add logic.

You might consider a CSS preprocessor. There are a few different "languages" that are very similar to CSS, but are more elaborate in terms of nesting and logic. An example is SASS. I know SASS can do this for you.

A CSS preprocessor then converts these SASS files to a normal CSS file.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. My hope was to keep the .css that my project shipped small by not having to compile all of the variations of the class.
unfortunately I don't think there is an option, CSS has no control flow
0

In scss, you can do something like this :

@for $i from 1 through 3 {
    .bg-color-#{$i} {
        background-color: var(--color-#{$i});
    }
}

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.