3

Is there a way to dynamically pick between the two colors below based on a class on the body without adding the body class to every less snippet that contains the color using less?

@basketballColor: #ff9900;
@footballColor: #99743d;

Can we do this?

.navbar-inner {
    background-color: @mainColor;
 }

I know we can do this but would like to condense it

body.basketball {

            .navbar-inner {
                background-color: @basketballColor;
            }
        }

body.football {

            .navbar-inner {
                background-color: @footballColor;
            }
        }
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341
  • No, I don't think it is possible to dynamically assign color based on the `class` assigned to the `body` (or any tag for that matter). Second option (or writing a loop) would be the better choice. – Harry Sep 30 '14 at 13:33
  • It doesn't seem possible (maybe with the JavaScript version). You could look into this answer: http://stackoverflow.com/a/15368587/3695983. – Alvaro Montoro Sep 30 '14 at 13:54

1 Answers1

4

This is quite often asked here at SO:

Just condense it via mixins, it is as simple as:

// usage:

body {
    .navbar(basketball, #ff9900);
    .navbar(football,   #99743d);
}

// impl:

.navbar(@name, @color) {
    &.@{name} .navbar-inner {
        background-color: @color;
    }
}

Or alternatively:

// usage:

.navbar(basketball, #ff9900);
.navbar(football,   #99743d);

// impl:

.navbar(@name, @color) {
    body.@{name} .navbar-inner {
        background-color: @color;
    }
}
Community
  • 1
  • 1
seven-phases-max
  • 11,765
  • 1
  • 45
  • 57
  • 1
    Or maybe call them within a loop if in case there are more such class-color combinations. – Harry Oct 01 '14 at 03:43
  • Thanks for sharing. Just to point out that in `body.@{name}` you do need to ADD curly braces around `name` to get the text from `@name` otherwise it would not work. I spent a few minutes here till I realised the issue I had. – seedme Apr 20 '22 at 00:47