Search code examples
variableslessmixins

LESS CSS Variable based on variable


I'm using LESS to build a site, and want the layout to switch based on direction, either 'ltr' or 'rtl' (direction:rtl)

I set @direction at the top. Then there are certain elements that I want floated left for ltr, and right for rtl. I also want to position absolute, and apply padding-left/right based on the @direction.

Instead of writing out separate mixins for float, pos and padding, I was trying to do something like this:

.mixin (@direction) when (@direction = ltr) {
    @lr:left;
}
.mixin (@direction) when (@direction = rtl) {
    @lr:right;
}

Then call it like this:

ol li {
    float:@lr;
}

and/or

ol li span.date {
    position:absolute;
    @lr:0;
}

That's the idea, but any help would be appreciated. I've looked at guards, and parametric mixins but just can't seem to nail it.


Solution

  • OK. After some playing and a bit of thinking this is what I've come up with. If I can't use variables as properties then I'll use @direction, and @directionOpp (opposite of rtl, ltr) to use as a layout helper.

    I have 2 variables.

    @direction:     ltr; // Change to 'rtl' for arabic, hebrew, etc.
    @directionOpp:  rtl; // Make this opposite of @direction, for easier mixins
    

    Here's my mixin for horizontal positioning.

      #dir {
        .dir(ltr,@dist:0) {left: @dist;}
        .dir(rtl,@dist:0) {right: @dist;}
        .float(ltr){float:left; }
        .float(rtl){float:right;}
        .margin(ltr, @dist:@a){margin-left:@dist;}
        .margin(rtl, @dist:@a){margin-right:@dist;}
        .padding(ltr, @dist:@a){padding-left:@dist;}
        .padding(rtl, @dist:@a){padding-right:@dist;}
      }
    

    and here's how I call it.

    ol li {
        #dir.float(@direction);
        #dir.padding(@direction);
    }
    

    If I ever need to reverse anything, then I can replace @direction with @directionOpp.

    I can also specifiy how much @dist I need as it's parametric mixin, and since they're all separate I can have any combination of margin, float, padding etc I need without multiple mixins with hard coded properties.

    Good solution? Dave