LESS mix-in for nth-child?

recursive picture recursive · Aug 8, 2013 · Viewed 21.5k times · Source

I'm trying to make a LESS mixin that will give me this output:

.resource:nth-child(8n+1) { clear: left; }

I've got this so far:

.wrap-every(@n) {
    &:nth-child(@n + "n+1") {  // parse error on this line
        clear: left;
    }
}

.resource {
    .wrap-every(8);
}

But it's giving a parse error on the indicated line

ParseError: Unrecognised input

Is there a way to do this?

Answer

Martin Turjak picture Martin Turjak · Aug 8, 2013

Less >= 1.4

you could do something like this:

.wrap-every(@n) {
  &:nth-child(@{n}n + 1) {
        clear: left;
    }
}

this should have the desired output. Without any hacks needed.

in older versins of Less

you can try simple string interpolation:

.wrap-every(@n) {
    @t: ~":nth-child(@{n}n + 1)";
    &@{t} {
        clear: left;
    }
}

and the output CSS in both cases should be something like this:

.resource:nth-child(8n + 1) {
  clear: left;
}