Reputation: 1126
I've seen plenty of posts on how to alternate the background color of a list or row.
$('#news tbody').each(function() {
$(this).children('tr:odd').addClass('alt');
});
I get it. But what if I wanted to have an alternating background for three rows. In other words the first one would have one color, the second another color, the third another color and then repeat. I've only been able to successfully add a background color to every third without overlap. Any suggestions?
Upvotes: 1
Views: 136
Reputation: 66
Use the pseudo class :nth-of-type
So for example, you could use
tr:nth-of-type(2)
{
background-color: red;
}
That will change the second row to red. But you could use a formula with n to get rows repeating, so for instance nth-of-type(3n+2) would give you the 2nd row (n = 0), then the fifth row (n = 1), then the eighth row (n = 2) and so on. Once you get your formulas just right, you can play with rows however you like.
If you also want the first row to be different (i.e. headers), just use (1).
Upvotes: 0
Reputation: 337580
You can do this in pure CSS using the nth-child
selector:
#news tbody tr:nth-child(3n+1) {
background-color: #C00;
}
#news tbody tr:nth-child(3n+2) {
background-color: #0C0;
}
#news tbody tr:nth-child(3n+3) {
background-color: #00C;
}
Alternatively you can achieve this in jQuery using an array and the modulo operator:
var classes = ['first', 'second', 'third'];
$('#news tbody tr').each(function(i) {
$(this).addClass(classes[i % classes.length]);
});
Upvotes: 5
Reputation: 27092
You can use just :nth-child in your CSS, no JavaScript needed. http://www.quirksmode.org/css/selectors/nthchild.html
Upvotes: 0