How to use css rules depending on an environment variable at runtime

  Kiến thức lập trình

How to use css rules depending on an environment variable. That is, I want to apply styles conditionally in a .scss that is based on the value of an environment variable (which evaluates to true or false).

I have found this option but it would be at build process:

@if $APPLY_STYLES == true { 
   .element .apply-style {
       color: blue; 
   }
}

I am interested in doing it at runtime, how could I do it? For example, if I do it this way, it matter the order of the class name in the rule so, i.e. in this example there is only one class but what happens if there are several defining a higher specificity? When you add the class, where does it add? Should be .element .apply-style or .element.apply-style

<style>
    .element {
        color: black; /* Default case */
    }
    .element .apply-style {
        color: blue; /* If APPLY_STYLES is true */
    }
</style>
<script>
    const applyStyles = this.env.APPLY_STYLES;
    const element = document.querySelector('.element');

    if (applyStyles === 'true') {
        element.classList.add('apply-styles');
    }
</script>

In any case, I don’t know if this is the best practice to do this.

LEAVE A COMMENT