htmlcsscss-selectors

Is there a way to use the "n" value in :nth-child(n)?


I want to create a fold effect.

Fiddle

There are 4 blue cards, so I created 4 classes to set the location. I want to make it smarter, in case there would be more than 4 cards. In CSS, I tried this.

.card:nth-child(n){
    position: absolute;
    left: calc(n*10)px;
    top: calc(n*10)px;
}

However, it does not work. Is there a way to do that?


Solution

  • CSS doesn't have support for variables. You could use Less/SASS loops and define it for n up to some value, but that would output almost the same CSS multiple times. Here is Codepen example.

    SCSS code to support up to 10 cards:

    $n: 10;
    
    @for $i from 1 through $n {
      .card:nth-child(#{$i}) {
        position: absolute;
        left: 10px * $i;
        top: 10px * $i;
      }
    }
    

    But are you sure your approach is correct? Maybe you want to take a step back and look for a different approach. Because this still doesn't scale dynamically, you'll have to predict or limit n to some value. If you were to pick large n, it would result in a big CSS file, which equals longer load times.