Less Mix-In for Nth-Child

LESS mix-in for nth-child?

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

Create mixin with nth-child

I think this would work

.test(@columns, @top-margin, @right-margin){
&:nth-child(@{columns}n){

}
}

For more info on nth child https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

LESS - use nth-child variable in string

#bg-slider {
li {
.bkg(1);
.bkg(2);
.bkg(3);
}

.bkg(@i) {
&:nth-child(@{i}) {
background: url('../images/bg@{i}.jpg');
}
}
}

LESS Mixin for loop

Looking at the docs I'd say it would look like:

.foo(4);

.foo(@n, @i: 1) when (@i =< @n) {
&:nth-child(@{i}) {
.animation-delay(100ms + (@i * 20));
}
.foo(@n, (@i + 1));
}

Tested with LESS2CSS using animation-delay property instead of your function:

.foo(4);

.foo(@n, @i: 1) when (@i =< @n) {
&:nth-child(@{i}) {
animation-delay: (100ms + (@i * 20));
}
.foo(@n, (@i + 1));
}

Generates:

:nth-child(1) {
animation-delay: 120ms;
}
:nth-child(2) {
animation-delay: 140ms;
}
:nth-child(3) {
animation-delay: 160ms;
}
:nth-child(4) {
animation-delay: 180ms;
}

less mixin or selector to change position based on sibling index?

Assuming you know the number of elements in advance (or are recalculating your css on the fly somehow), then essentially what you have works if put into a loop structure which I originally discovered here on stack overflow.

LESS Code

.loop(@index) when (@index > 0) {
//set top amount
&:nth-of-type(@{index}) { //NOTE: 1.3.3 and under is just @index, not @{index}
top: @index * 20px;
}

// next iteration
.loop(@index - 1);
}

// end the loop when index is 0
.loop(0) {}

.yourElem {
@n: 6; //num of elements (could skip this and just put number in)
.loop(@n);
}

Outputs

.yourElem:nth-of-type(6) {
top: 120px;
}
.yourElem:nth-of-type(5) {
top: 100px;
}
.yourElem:nth-of-type(4) {
top: 80px;
}
.yourElem:nth-of-type(3) {
top: 60px;
}
.yourElem:nth-of-type(2) {
top: 40px;
}
.yourElem:nth-of-type(1) {
top: 20px;
}


Related Topics



Leave a reply



Submit