A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

[Proposal] Expose the index value (n) in an nth-child selector?

Th3S4mur41
2021-10-05

Being able to use the index of the current child as value would make several use cases possible without the need to use javascript.

It would for instance be extremely helpful to use as multiplicator to gradually delay animations. A way to currently achieve this requires the index to be set in a CSS custom properties via JavaScript (to e.g. create an HTML list as below)

<ul>
  <li style="--index: 0"></li>
  <li style="--index: 1">/li>
  ...
  <li style="--index: n">/li>
</ul>

li:nth-child(n) {
	animation: reveal 1s linear calc(var(--index, 0) * 0.5s) both;
}

@keyframes reveal {
	from { opacity: 0; }
	to { opacity: 1; }
}

Being able to access the index directly in CSS, would simplify use cases as above and make them possible with CSS only.

The same example could be implemented as below… Note that the use of the ‘env()’ function is just meant as an example of a way this could be done, but there might be better suited approaches.

li:nth-child(n) {
	animation: reveal 1s linear calc(env(n) * 0.5s) both;
}

@keyframes reveal {
	from { opacity: 0; }
	to { opacity: 1; }
}
leaverou
2021-10-08

Or, alternatively, a way to convert strings to numbers would help with these use cases, because then you can use counters. Note that this would be strictly more powerful, as you could choose how to count.

jimmyfrasche
2021-10-08

This looks like: https://github.com/w3c/csswg-drafts/issues/4559