MakeThePainStop
MakeThePainStop

Reputation: 101

How to set a css class property dynamicaly

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>

Upvotes: 0

Views: 47

Answers (2)

Remco Kersten
Remco Kersten

Reputation: 156

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.

Upvotes: 1

Yanan LYU
Yanan LYU

Reputation: 1

In scss, you can do something like this :

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

Upvotes: 0

Related Questions