Short description (tl; dr;)
Is there a way to "pure CSS" (not Less / Sass) using the nth-child value inside CSS properties? Something like that:
span.anim:nth-child(N) { animation-delay: N * 0.5s; }
If so, how can I do this? If not, how could I simulate this in a clean way? (I'm sure I'm over complicating here)
Long description
I created a simple animation in which letters disappear during rotation. For this I used a combination of javascript (with jQuery) and CSS, but this created some problems (see below); so I tried moving on to the CSS single solution, and it ended up with a lot of rules.
This (simplified) CSS is common to both solutions:
span.anim { font-size:30px; opacity:0; animation: anim 1s; animation-fill-mode: forwards; } @keyframes anim { from { transform: rotate(0deg); opacity:0; } to { transform: rotate(360deg); opacity:1; } }
Using JavaScript + CSS
My JavaScript code is as follows:
var aux = $("#animate").text(); $("#animate").text(""); for (var x = 0; x < aux.length; x++) { setTimeout('$("#animate").append("<span class=\'anim\'>' + aux[x] + '</span>")', 500 * x); }
This works fine ... if the user does not move to another tab, then the animation will get confused and the result will be unexpected. You can see this on this JSFiddle: http://jsfiddle.net/e7b9ygk4/ (run the script, go to another tab and come back in a few seconds).
Using CSS Only
I can achieve the same effect by breaking the element into smaller elements (this is the part that I feel that I'm too complicated), and then applying the animation to each element with a different delay:
span.anim:nth-child(1) { -webkit-animation-delay:0.5s; } span.anim:nth-child(2) { -webkit-animation-delay:1.0s; } span.anim:nth-child(3) { -webkit-animation-delay:1.5s; } span.anim:nth-child(4) { -webkit-animation-delay:2.0s; } span.anim:nth-child(5) { -webkit-animation-delay:2.5s; } span.anim:nth-child(6) { -webkit-animation-delay:3.0s; } span.anim:nth-child(7) { -webkit-animation-delay:3.5s; } span.anim:nth-child(8) { -webkit-animation-delay:4.0s; } span.anim:nth-child(9) { -webkit-animation-delay:4.5s; } span.anim:nth-child(10) { -webkit-animation-delay:5.0s; } span.anim:nth-child(11) { -webkit-animation-delay:5.5s; } span.anim:nth-child(12) { -webkit-animation-delay:6.0s; } span.anim:nth-child(13) { -webkit-animation-delay:6.5s; } span.anim:nth-child(14) { -webkit-animation-delay:7.0s; } span.anim:nth-child(15) { -webkit-animation-delay:7.5s; } span.anim:nth-child(16) { -webkit-animation-delay:8.0s; }
This works great even if the user switches to another tab, but leads to a lot of unnecessary code (both HTML and CSS, although it can be simplified using JavaScript). You can see how it works on this JSFiddle: http://jsfiddle.net/f5my3sm1/ .
My gut tells me that this can be achieved with Sass / Less, but I want to know if there is an easy way for βpure CSSβ to do this, which can be achieved (hopefully) with one rule:
span.anim:nth-child(N) { animation-delay: N * 0.5s; }