Skip to content

Instantly share code, notes, and snippets.

@danro
Last active October 7, 2019 09:37
Show Gist options
  • Save danro/6196732 to your computer and use it in GitHub Desktop.
Save danro/6196732 to your computer and use it in GitHub Desktop.
LESS css loop example
.loop (0) {}
.loop (@index) when (@index > 0) {
.classname-@{index} {
top: @index * 1px;
}
.loop (@index - 1);
}
#example {
.loop(5);
}
#example .classname-5 {
top: 5px;
}
#example .classname-4 {
top: 4px;
}
#example .classname-3 {
top: 3px;
}
#example .classname-2 {
top: 2px;
}
#example .classname-1 {
top: 1px;
}
Copy link

ghost commented Jul 14, 2014

What is the top .loop (0) {} there for? Just trying to understand this.

@JeffSallans
Copy link

The top .loop(0) {} is the base case, while .loop(index -1) is the recursive case.
You may see examples without the base case. Those cases are assuming .loop(0) is not implemented.

@marocas
Copy link

marocas commented Sep 13, 2016

Hello, can we multiply the index for any value?
In SCSS we can do this:

$class-slug: spacer !default;
@for $i from 1 through 20 {
    &.#{$class-slug}-#{$i*5} {
        width: 100%;
        max-width: 600px;
        height: ($i*5px);
        max-height: ($i*5px);
        min-height: ($i*5px);
        line-height: ($i*5px);
        font-size: ($i*5px);
    }
}

You can check here the output http://www.sassmeister.com/
Now i can say that my class-(index*5), can we do this with LESS?

Best regards, Mário Silva.

@goeko
Copy link

goeko commented Feb 21, 2018

            @max-grid-items : 20;
            .grid-row-loop (0) {}
            .grid-row-loop (@index) when (@index > 0) {
              @nextIndex : (@index * 2);
              @prevIndex : (@nextIndex - 1);
              &:nth-child(@{prevIndex}) {
                grid-row: @index;
              }
              &:nth-child(@{nextIndex}) {
                grid-row: @index;
              }
              .grid-row-loop (@index - 1);
            }
            .grid-row-loop (@max-grid-items);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment