Dean Elliott
Dean Elliott

Reputation: 729

nth-child, assign styles to every element that is a multiple of 4

I have a 4 column grid based layout and I want to apply CSS3 animations in a similar way to this;

<div class="block"></div><!-- animation-duration: 1s -->
<div class="block"></div><!-- animation-duration: 2s -->
<div class="block"></div><!-- animation-duration: 3s -->
<div class="block"></div><!-- animation-duration: 4s -->
<div class="block"></div><!-- animation-duration: 1s -->
<div class="block"></div><!-- animation-duration: 2s -->
<div class="block"></div><!-- animation-duration: 3s -->
<div class="block"></div><!-- animation-duration: 4s -->

So basically, items in the first column have an animation duration of 1s, items in the second column have a 2s animation duration, etc. etc.

How can I achieve this with nth-child?

Upvotes: 3

Views: 224

Answers (2)

apsillers
apsillers

Reputation: 115950

To answer your question as written, you'll need four styles, one for each animation duration:

.block:nth-child(4n) {
    animation-duration: 1s;
}

.block:nth-child(4n+1) {
    animation-duration: 2s;
}

.block:nth-child(4n+2) {
    animation-duration: 3s;
}

.block:nth-child(4n+3) {
    animation-duration: 4s;
}

The :nth-child syntax of an + b allows you to indicate your looping frequency with a and your initial offset with b. Each duration style needs its own b offset.

However, if you want to generalize this to m styles (instead of just 4), you should probably apply styles through a script, rather than writing them by hand.

Upvotes: 5

Milind Anantwar
Milind Anantwar

Reputation: 82241

If You are looking for jquery code then try this:

Working Fiddle

$(document).ready(function(){
$('#maindiv .block').each(function(){
duration=($(this).index()%4+1)*1000 ;
$(this).css('animation-duration',($(this).index()%4+1)+'s')
})
})

Upvotes: 0

Related Questions