How to optimize my LESS mixin?

58 Views Asked by At

This mixin generates helper classes for Bootstrap.

I'm sure there is way to improve this mixin using loops.

.generate-margin-tops(@size) {
  .mt-@{size}-5 {
    margin-top: 5px;
  }

  .mt-@{size}-10 {
    margin-top: 10px;
  }

  .mt-@{size}-20 {
    margin-top: 20px;
  }

  .mt-@{size}-30 {
    margin-top: 30px;
  }

  .mt-@{size}-40 {
    margin-top: 40px;
  }
}

Snippet using for different screen dimensions:

.generate-margin-tops(xs);

@media (min-width: @screen-sm-min) {
  .generate-margin-tops(sm);
}

@media (min-width: @screen-md-min) {
  .generate-margin-tops(md);
}

@media (min-width: @screen-lg-min) {
  .generate-margin-tops(lg);
}

P.S. See the my final solution

2

There are 2 best solutions below

4
On BEST ANSWER

This can be simplified using loops like below (explanation in-line in comments):

.generate-margin-tops(@size, @index) when (@index > 0) {
    @margin-top: extract(@margin-px, @index); //extract the margin value corresponding to the index/counter variable
    .mt-@{size}-@{margin-top} { //selector interpolation to form the selector
        margin-top: unit(@margin-top,px); //converts plain number to px units
    }
    .generate-margin-tops(@size, @index - 1); //call to the next iteration by decrementing the counter
}

@margin-px: 5, 10, 20, 30, 40; //array list variable which contains the various margin pixels

.generate-margin-tops(xs, length(@margin-px)); //call to loop mixin

@media (min-width: @screen-sm-min) {
  .generate-margin-tops(sm, length(@margin-px));
}

@media (min-width: @screen-md-min) {
  .generate-margin-tops(md, length(@margin-px));
}

@media (min-width: @screen-lg-min) {
  .generate-margin-tops(lg, length(@margin-px));
}
0
On

@Harry greatly helped me to deal with cycles in the less. Eventually I came to this solution:

@margin-tops: quarter 0.25, half 0.5, one 1, two 2, three 3, four 4;

.generate-margin-tops(@suffix: ~'', @i: 1) when (@i =< length(@margin-tops)) {
  @item:  extract(@margin-tops, @i);
  @key:   extract(@item, 1);
  @value: extract(@item, 2);

  .mt-@{key}@{suffix} {
    margin-top: @line-height-computed * @value;
  }

  .generate-margin-tops(@suffix, @i + 1);
}

The result of .generate-margin-tops(-sm) is:

.mt-quarter-sm { margin-top: 5px }
.mt-half-sm { margin-top: 10px }
.mt-one-sm { margin-top: 20px }
.mt-two-sm { margin-top: 40px }
.mt-three-sm { margin-top: 60px }
.mt-four-sm { margin-top: 80px }