LESS condition based on CSS class to set a LESS variable

Variables in Less are actually constants and will only be defined once.

Scope works within its code braces, so you would need to nest your CSS within each theme you want (which means duplication).

This is not ideal as you would need to do this:

body.themeBlue {
  @color: blue;
  /* your css here */
}

body.themeRed {
  @color: red;
  /* your css here AGAIN :( */
}

You could, however, try to use variables like this:

@color: black;
@colorRed: red;
@colorBlue: blue;

h1 {
  color: @color; // black
  body.themeRed & {
    color: @colorRed; // red
  }
  body.themeBlue & {
    color: @colorBlue; // blue
  }
}

You would only need to declare the colours once, but you would need to constantly do the "body.themeRed" etc. prefixes where the colour varies depending on the theme.


You could actually use @import to load your theme! So common.less would contain all your default styles and @themeColor will be applied to it.

.mainThemeDependentCss() {
  //file with all themed styles
  @import 'common.less';
}

//use the mixin in the themes
body.themeBlue {
  @themeColor: blue;
  .mainThemeDependentCss();
}

body.themeRed {
  @themeColor: red;
  .mainThemeDependentCss();
}

BTW you should avoid using body selector in your common.less, because it wouldn't work.


The LESS file cannot read the actual class applied to the html body element at run time (you would probably need to implement a javascript solution to do something like that).

If you just want to have all themed css ready for use based on the body class, the best way to implement this to have all the necessary theme based css in a mixin, then apply it under the theme classes. This reduces code duplication. For example:

LESS

//mixin with all css that depends on your color
.mainThemeDependentCss() {
  @contrast: lighten(@themeColor, 20%);
  h1 {color: @themeColor;}
  p {background-color: @contrast;}
}

//use the mixin in the themes
body.themeBlue {
  @themeColor: blue;
  .mainThemeDependentCss();
}

body.themeRed {
  @themeColor: red;
  .mainThemeDependentCss();
}

CSS Output

body.themeBlue h1 {
  color: #0000ff;
}
body.themeBlue p {
  background-color: #6666ff;
}
body.themeRed h1 {
  color: #ff0000;
}
body.themeRed p {
  background-color: #ff6666;
}

For some other answers that deal with aspects or ways of theming, see:

  • LESS CSS - Change variable value for theme colors depending on body class
  • LESS.css variable depending on class
  • LESS CSS: abusing the & Operator when nesting?

Tags:

Less