Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variables inside :nth-child(n + x) pseudo class

At the moment I have a snippet of LESS that will basically shift each subsequent child further down from the top:

    &:nth-child(n+2) {
        top: @alertTop + 10px;
    }

    &:nth-child(n+3) {
        top: @alertTop + 20px;
    }

    &:nth-child(n+4) {
        top: @alertTop + 30px;
    }

Is there anyway to use the 'x' part of 'n+x' in the calculation so that I don't have to manually add these?

I.e. something like:

    &:nth-child(n+x) {
        top: @alertTop + (x * 5px);
    }

LESS/CSS only methods preferred.

like image 551
Adam Marshall Avatar asked Oct 19 '22 21:10

Adam Marshall


1 Answers

From the documentation: Create a mixin that calls itself, along with a guard expression:

LESS

#test {
  @child-count: 5;
  @child-height: 100px;
  position: relative;
  height: @child-count * @child-height;
  > div {
    position: absolute;
    left: 0;
    right: 0;
    height: @child-height;
    background: red;
  }
  .loop(@i) when (@i <=5) {
    > :nth-child(@{i}) {
      top: (@i - 1) * @child-height;
    }
    .loop(@i + 1);
  }
  .loop(1);
}

Result

#test {
  position: relative;
  height: 500px;
}
#test > div {
  position: absolute;
  left: 0;
  right: 0;
  height: 100px;
  background: red;
}
#test > :nth-child(1) {
  top: 0px;
}
#test > :nth-child(2) {
  top: 100px;
}
#test > :nth-child(3) {
  top: 200px;
}
#test > :nth-child(4) {
  top: 300px;
}
#test > :nth-child(5) {
  top: 400px;
}

CodePen

like image 139
Salman A Avatar answered Oct 22 '22 23:10

Salman A