Search code examples
twitter-bootstraplessless-mixins

How to optimize my LESS mixin?


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


Solution

  • 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));
    }