使用 nth-child 作为 CSS 变量 [英] Use nth-child as CSS variable

查看:40
本文介绍了使用 nth-child 作为 CSS 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法(不用 javascript)可以让 nth-child 影响 CSS?

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

例如,当我加载了 10 张图片时,我会淡入不透明度,并为每张图片设置 N 秒的动画延迟.

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

我可以使用 nth-child(1){}、nth-child(2){} 等手动执行此操作,但这显然很混乱并且元素数量有限.

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.

我也尝试过循环,虽然这对 (10n+1) 效果很好,但如果我试图偏离 an+b 公式 (100n+10n),它就会中断.此外,我怀疑每 n 增加 1 秒,每 10n 增加 10 秒是否可行,因为其中一个会覆盖另一个.

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.

这个问题类似于 2011 年的这个问题 仍然开放,但已经过去了很多时间,也许这些天有更好的答案.

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.

推荐答案

请记住,您也可以在 CSS 中分配变量.

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;

这里有一些演示.

这篇关于使用 nth-child 作为 CSS 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆