Clear mixin for Less not working using When Guard

2019-06-14 01:00发布

问题:

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

回答1:

#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);


标签: css less