Use nth-child as CSS variable

后端 未结 2 1904
挽巷
挽巷 2020-12-16 19:54

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 ima

相关标签:
2条回答
  • 2020-12-16 20:27

    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.

    0 讨论(0)
  • 2020-12-16 20:37

    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.

    0 讨论(0)
提交回复
热议问题