Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
Kent Wood Avatar asked Jan 17 '15 18:01

Kent Wood


2 Answers

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.

like image 70
Marko Gresak Avatar answered Sep 23 '22 00:09

Marko Gresak


To leave calculations in CSS, you can use CSS variables: calc( var(--n) * 10px );. You'll still have to define --n manually either via JS or by having it predefined in the HTML, but this way it feels more declarative, as no actual styling make it to JS code:

function add() {
  var parent = document.querySelector('.container');
  var child = document.createElement('div');
  child.classList.add('child');
  child.style.setProperty('--n', parent.children.length);
  parent.appendChild(child);
}
.child {
  position: absolute;
  left: calc( var(--n) * 30px + 100px );
  top: calc( var(--n) * 30px );
  background-color: red;
  width: 30px;
  height: 30px;
}
<button onclick="add()">Add more</button>
<div class="container">
  <div class="child" style="--n: 0;"></div>
  <div class="child" style="--n: 1;"></div>
  <div class="child" style="--n: 2;"></div>
</div>

Browser support is pretty decent: every major browser nowadays has it.

like image 40
user Avatar answered Sep 26 '22 00:09

user