Use nth-child as CSS variable

2020-02-11 02:29发布

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.

1条回答
成全新的幸福
2楼-- · 2020-02-11 03:34

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.

查看更多
登录 后发表回答