norbidrak norbidrak - 2 months ago 10
Less Question

Add different values(incrementing) to different elements of the same type - LESS CSS

I would like to add

"top"
value to different paragraphs in certain class. The thing is that each paragraph has to have different, incremented value like
"top: 30px + something"
, increasing regularly with another paragraph. Paragraphs don't have unique selectors.

.class p{ //1st element
top: 50px;
}
.class p{ //2nd element, and so on...
top: 70px;
}


Is there a way to automate this with LESS ??

Answer

You have to know the number of paragraphs, otherwise isn`t possible for LESS read the HTML. If you know the number of paragraphs you can do a loop and increment the value for each iteration:

LESS

.paragraphs(4);

.paragraphs(@n, @i: 1) when (@i =< @n) {
  .class p:nth-child(@{i}) {
    top: (@i * 20px + 30);
  }
  .paragraphs(@n, (@i + 1));
}

Output

.class p:nth-child(1) {
  top: 50px;
}
.class p:nth-child(2) {
  top: 70px;
}
.class p:nth-child(3) {
  top: 90px;
}
.class p:nth-child(4) {
  top: 110px;
}
Comments