4

I'm looking at code like this:

.my-element:nth-child(1) {
  -moz-transition-delay: 0.1s;
  -o-transition-delay: 0.1s;
  -webkit-transition-delay: 0.1s;
  transition-delay: 0.1s;
}
.my-element:nth-child(2) {
  -moz-transition-delay: 0.2s;
  -o-transition-delay: 0.2s;
  -webkit-transition-delay: 0.2s;
  transition-delay: 0.2s;
}
.my-element:nth-child(3) {
  -moz-transition-delay: 0.3s;
  -o-transition-delay: 0.3s;
  -webkit-transition-delay: 0.3s;
  transition-delay: 0.3s;
}

Is there a way in CSS only to do some sort of loop, i.e in sudo code:

For each element, delay fadein + 0.1s

Then I will get the effect of having each row fade in one after the other without having to specifically write CSS for nth child all the way up to 50. This is my test HTML table to test:

https://jsfiddle.net/268n9gcq/

Is this possible without having to use javascript?

Jimmy
  • 12,087
  • 28
  • 102
  • 192
  • can you use a CSS preprocessor lise sass? – Fabrizio Calderan Jan 22 '16 at 10:34
  • @FabrizioCalderan I might be able to, but there are likely to be at least 50 rows in the table, will this cause performance issues? – Jimmy Jan 22 '16 at 10:36
  • Sass is a preprocessor that will compile to css at the end , so the performance impact will be the same either you choose to use it or not. It'll definitely help you maintain a DRYier code @Jimmy – Vangel Tzo Jan 22 '16 at 10:38
  • sass can output a CSS with all those 50 rules with a `for` loop. this will save you from inserting css by hand - see http://codepen.io/anon/pen/zrRxGJ?editors=0100 (view compiled source) – Fabrizio Calderan Jan 22 '16 at 10:38
  • 3
    Possible duplicate of [CSS Animations with delay for each child element](http://stackoverflow.com/questions/8294400/css-animations-with-delay-for-each-child-element) – Pete Jan 22 '16 at 10:44
  • 1
    This would be better solved in JS, a CSS file is going to balloon in size the more table rows you have. If you're ok with that, Sass is probably the best solution as Fabrizio Calderan said. – gaynorvader Jan 22 '16 at 10:48

1 Answers1

1

To do this with only CSS you'll need to create nth-child() rules as you've already started. Less, Sass or another compiler will help keep your code more manageable, and create a CSS-only solution at the same time.

In the CSS compiler you'll create a loop similar to this (for SCSS):

@for $i from 1 through 10 {
  tr:nth-child(#{$i}) {
    $time: $i * 3 + unquote('');
    $delay: unquote('0.' + $time + 's');
    animation-name: showRow;
    animation-duration: 1s;
    animation-delay: $delay; 
    animation-timing-function: ease-in;
  }
}
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184