Search code examples
htmlcssvariablesstylesless

Pass a value from HTML to CSS


I was interested whether can I pass value to the css class from the html? Like this Example:

<div class="mt(5)"> Some text </div>
style {
 .mt(@mpx) {
   margin-top: @mpx px;
 }
}

I've heard that such way was possible in Less


Solution

  • No, the way you want it is impossible in either CSS or any of its supersets (like Less and others). It's always HTML that uses values from CSS and not in opposite. Thus you'll need some scripting for what you need.

    You can however pass values from HTML to CSS via Custom Properties using inline styles:

    .c {color:  var(--c)}
    .m {margin: var(--m)}
    <div class="c" style="--c: blue" >Foo</div>
    <div class="m" style="--m: 0 2em">Bar</div>
    <div class="c" style="--c: green">Baz</div>

    Or even like this:

    * {
        color:  var(--c);
        margin: var(--m);
        /* etc. */
    }
    <div style="--c: blue" >Foo</div>
    <div style="--m: 0 2em">Bar</div>
    <div style="--c: green">Baz</div>

    But that method is no way different from styling by the plain vanilla method, i.e.:

    <div style="color: blue"> 
    ... etc. 
    

    It is essentially same ugly and non-maintainable.


    Many people try to achieve the goal by generating hundreds of predefined classes like .mt-1, .mt-2, ... .mt-99 etc. (since it's extremely easy thing to do in a CSS-preprocessor). But it's even more ugly solution (I won't bother you with details on why it is so. You'll read about that elsewhere or learn yourself after a few projects).