Home > Net >  How to set a css class property dynamicaly
How to set a css class property dynamicaly

Time:10-21

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 >This background should be red</div>
<div >This background should be blue</div>
<div >This background should be yellow</div>

CodePudding user response:

In scss, you can do something like this :

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

CodePudding user response:

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.

  • Related