Miguel Moura
Miguel Moura

Reputation: 39484

Clear mixin for Less not working using When Guard

I am trying to create a simple less mixins for clear so I have:

.clear {

  &:after {
    content: "";
    display: table;
    clear: both;
  } // :after

}

.clear(@float) when (@float = "left", @float = "right") {
  clear: @float;
}

Basically I want to clear both when I use ".clear" or ".clear(both)" and the second one when I use .clear("left") or ".clear("right").

How can I do this?

Thank You, Miguel

Upvotes: 0

Views: 144

Answers (1)

seven-phases-max
seven-phases-max

Reputation: 11820

#1 The most straightforward way is to use default mixin guard:

.clear(...) when (default()) {
    &:after {
        content: "";
        display: table;
        clear: both;
    }
}

.clear(@float) when (@float = left), (@float = right) {
    clear: @float;
}

#2 Or:

.clear(...) when (default()) {
    &:after {
        content: "";
        display: table;
        clear: both;
    }
}

.clear(left)  {clear: left}
.clear(right) {clear: right}

#3 Or even more clean/optimal in this case (and also old Less versions compatible) Pattern Matching for all variant:

.clear() {
    &:after {
        content: "";
        display: table;
        clear: both;
    }
}

.clear(both)  {.clear()}
.clear(left)  {clear: left}
.clear(right) {clear: right}

---

... and the second one when I use .clear("left") or ".clear("right").

Don't use quotes there, correct usage would be:

.clear;
.clear();
.clear(both);
.clear(left);
.clear(right);

Upvotes: 2

Related Questions