Using guards in the mixin

174 views Asked by At

I want to create a clever mixin for Bootstrap sources (mixin->buttons.less).

What I have is as follows:

Less:

.button-variant(@color; @background; @border) {
  color: @color;
  background-color: @background;
  border-color: @border;

  /* this variables must be used when I have parent's  class="invert"*/
  color: @background;
  background: @color;
  border-color: @background;
  /* end */

  /*when not - use variables in the beggining of mixin */

}

How I see using this mixin

.btn-primary,
.btn-primary-invert{
    .button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
}

Can I do something like I want? I understand that it could be done with Less guards, but don't understand how to use it. Have anybody some ideas?

1

There are 1 answers

2
Harry On BEST ANSWER

The simplest approach would be to make use of the parent selector (&) like in the below snippet and forget using guards. Here the mixin by default produces both the normal and inverted state for all buttons. You can use this if you want both states to be applicable for all buttons.

.button-variant(@color; @background; @border) {
  &{
    &:hover, &:active{
      color: @color;
      background-color: @background;
      border-color: @border;
    }
  }
  &-invert{
    &:hover, &:active{
      color: @background;
      background: @color;
      border-color: @background;
    }
  }
}

.button-primary{
  .button-variant(#000; #fff; #777);
}

The above snippet when compiled would result in the following CSS:

.button-primary:hover,
.button-primary:active {
  color: #000000;
  background-color: #ffffff;
  border-color: #777777;
}
.button-primary-invert:hover,
.button-primary-invert:active {
  color: #ffffff;
  background: #000000;
  border-color: #ffffff;
}

If you really want to use guards for whatever preferences (like you don't want either of the states for a specific button), then you could use a snippet like the below. For using guards, you need to send an extra parameter which indicates the type based on which the guard can be verified.

.button-variant(@color; @background; @border; @type:normal) {
  & when (@type = normal){
    color: @color;
    background-color: @background;
    border-color: @border;
  }
  & when (@type = invert){
    color: @background;
    background: @color;
    border-color: @background;
  }
}

.button-primary{
  .button-variant(#000; #fff; #777);
}
.button-primary-invert{
  .button-variant(#000; #fff; #777; invert);
}