Search code examples
cssless

Using CSS variables in LESS


This might seem basic, but I can't figure out how to use CSS variables in LESS?

variables.css:

.root {
    --header-color: white;
    --content-color: yellow;
}

styles.less:

@import "../variables.css";
.header {
   color: @header-color;
}

I get error "@header-color is undefined".


Solution

  • LESS allows you to use normal CSS code, so use one option could be just use the variable as CSS:

    @import "../variables.css";
    .header {
       color: var(--header-color);
    }
    

    Also, you can save the css var to a LESS var:

    @import "../variables.css";
    @header-color: var(--header-color);
    
    .header {
       color: @header-color;
    }
    

    • WARNING: Is not possible to use css variables as parameters of less functions like color: darken(var(--header-color), 50%). Even if you saved previously in a less variable color: darken(@header-color, 50%). This is because Less needs to know the value of the variable at compile time, while CSS variables are resolved at runtime in the browser.