17

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?

recursive
  • 83,943
  • 34
  • 151
  • 241

1 Answers1

26

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;
}
Martin Turjak
  • 20,896
  • 5
  • 56
  • 76
  • 1
    +1 for including the new syntax of @{n}, because in previous version of less we could just use the @n syntax. – Shaun Luttin Jan 15 '14 at 19:52
  • Using a recent dotless (for .net) and the older version worked for me. Thanks. – Jarrod McGuire Sep 24 '17 at 21:44
  • 1
    This solved my problem! Just in case someone's searching, I was trying to include `nth-last-child` with a variable inside a mixin, and was getting the error `Missing closing ')'`. Was driving me bananas. `@{variable}` syntax inside `nth-last-child` fixed it! – Nathan Arthur Apr 18 '18 at 18:59
  • what is the syntax for `nth-last-child`? above technique not working for me – Sasikanth Nov 15 '18 at 05:08