css increment nth-child attribute values
Asked Answered
I

2

8

Is there a way to increment attribute values using n in nth-child(n) to output the result of:

div:nth-child(1){
    top: -5px;
}
div:nth-child(2){
    top: -10px;
}
div:nth-child(3){
    top: -15px;
}
div:nth-child(4){
    top: -20px;
}
div:nth-child(5){
    top: -25px;
}
Impeller answered 17/11, 2014 at 13:3 Comment(2)
There is if you use a preprocessor like sass for exampleBorszcz
...or add it with jquery: $('div').each(function(i=1){$(this).css("top", -5*i); i++;});Impeller
B
12

You could if you use a preprocessor like sass.

An example:

div {
  $var: 5;

  @for $i from 1 through 5 {
    &:nth-child(#{$i}) {
      top: -#{$var}px;
      $var: $var + 5;
    }
  }
}

A demo: http://sassmeister.com/gist/7d7a8ed86e857be02d1a

Another way to achieve this:

div {

  $list: 1 2 3 4 5;

  @each $i in $list {
    &:nth-child(#{$i}) {
      top: -5px * $i;
    }
  }
}

A demo: https://www.sassmeister.com/gist/fb5ee7aa774aafb896cd71a828882b99

Borszcz answered 17/11, 2014 at 13:10 Comment(3)
Can you post a foreach equivalent of the statement if number is dynamic?Impeller
But that only works if you know you have 5 elements. What if elements are added dynamically?Fabi
SCSS always translates in CSS so you can't have a dynamically variable. I suppose you're looking for a css only way to achieve this something like nth-child(n+1) { top: -5px * n} but unfortunately this won't work.Borszcz
B
0

I was able to increment my nth-child(n) by moving my selector to XPath. Certainly not optimal, but it works.

the XPath for my scraping code looks like:

for (b=1; b<5; b++) {
    await page.waitForXPath('//*[contains(concat( " ", @class, " " ), concat( " ", "table__tr", " " )) and (((count(preceding-sibling::*) + 1) = '+b+') and parent::*)]//*[contains(concat( " ", @class, " " ), concat( " ", "table__td", " " ))]');

    let elhandle = await page.$x('//*[contains(concat( " ", @class, " " ), concat( " ", "table__tr", " " )) and (((count(preceding-sibling::*) + 1) = '+b+') and parent::*)]//*[contains(concat( " ", @class, " " ), concat( " ", "table__td", " " ))]');

    let game = await page.evaluate(el => el.textContent, elhandle[0]);
    let ddd = await page.evaluate(el => el.textContent, elhandle[1]);
    oo = oo + '{","game":" ' + game +' ","date":" ' + ddd + ' "}, \n'
} // b

notice that XPath allows the b variable to be incremented.

Bladderwort answered 9/2, 2023 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.