Is it possible to use the nth-child value as a parameter in a property? (and how)

前端 未结 2 858
野的像风
野的像风 2020-12-15 10:46

Short description (tl;dr;)

Is there a \"pure CSS\" way (not Less/Sass) of using the value of the nth-child inside the CSS properties? Something like t

相关标签:
2条回答
  • 2020-12-15 10:58

    There is a very experimental CSS function for using attributes as properties for an element. Currently it only works on pseudo elements, so you'd have to consider coming up with some kind of clever re-working of your markup in this use case.

    You could put the offset in a data-attribute on your markup (or with JS), and then use something like the following:

    /* attr(name, units, fallback) */
    span.anim {animation-delay: attr(offset, 1) * 0.5s;}
    
    <span class="anim" offset="0"></span>
    <span class="anim" offset="1"></span>
    <span class="anim" offset="2"></span>
    <span class="anim" offset="3"></span>
    <span class="anim" offset="4"></span>
    

    Please keep in mind that this is still a ways off from being widely accepted, and like I mentioned before, the above syntax wouldn't work currently because it would need to use pseudo elements like :after.

    At the very least, it's something fun to think about.

    0 讨论(0)
  • 2020-12-15 10:59

    CSS variables have almost universal support on all modern browsers and can achieve virtually the same desired effect as @GreatBlake's answer using attr plus more. Instead of defining data in a user-defined attribute, you can define it as a custom property in the style attribute and get the value of those custom properties using the var() function:

    <span class="anim" style="--n: 0"></span>
    <span class="anim" style="--n: 1"></span>
    <span class="anim" style="--n: 2"></span>
    <span class="anim" style="--n: 3"></span>
    <span class="anim" style="--n: 4"></span>
    
    span.anim {
      animation-delay: calc(var(--n) * 0.5s);
    }
    
    0 讨论(0)
提交回复
热议问题