Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use nth-child as CSS variable

Is there some way (without javascript) to make the nth-child affect the CSS?

For example when I have 10 images loaded, I would fade the opacity in, and give each image an animation delay of N seconds.

I can do this manually with nth-child(1){}, nth-child(2){} and so on, but that's obviously messy and has a finite amount of elements.

I have also tried loops and while that works out well for (10n+1), it breaks if i try to stray from the an+b formula (100n+10n). Also I doubt it would work to add 1 second for every n and 10 seconds for every 10n because one of those would overwrite the other.

This question is similar to this one from 2011 which is still open but a lot of time has passed and maybe there's a better answer these days.

like image 754
PixelSnader Avatar asked Aug 04 '17 13:08

PixelSnader


People also ask

How do I select a specific Nth child in CSS?

Definition and Usage The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

How do I select a child in CSS?

Child Selector: Child Selector is used to match all the elements which are children of a specified element. It gives the relation between two elements. The element > element selector selects those elements which are the children of the specific parent.

What is the nth child in CSS?

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.


2 Answers

Please remember that you can assign variables in CSS too.

:nth-child(1) { --nth-child: 1 }
:nth-child(2) { --nth-child: 2 }
:nth-child(3) { --nth-child: 3 }

Then you can apply it like this:

animation: fade-in calc(var(--nth-child) * 1s) 1s forwards;

And here come some demo.

like image 118
Audi Nugraha Avatar answered Oct 10 '22 14:10

Audi Nugraha


CSS does not support using the current value of n, or the index of the child element currently being matched, from an :nth-child() expression as a variable, neither in calc() expressions nor var() expressions nor any other part of a property value.

The closest you can get is automating the manual process using a preprocessor that does support interpolating variables within selectors. This will work if you know the number of rules you need to build in advance, but only then.

like image 27
BoltClock Avatar answered Oct 10 '22 15:10

BoltClock