CSS Alternate Rows - some rows hidden

Andy picture Andy · Jun 2, 2011 · Viewed 10.7k times · Source

I'm trying to style a table so that each row is a different colour (odd/even). I have the following CSS:

#woo tr:nth-child(even) td {
    background-color: #f0f9ff;
}

#woo tr:nth-child(odd) td {
    background-color: white;
}

However, some of my rows can be hidden and I'd still like the rows to alternate. How can I adjust the above so it gives the appearance of alternate rows, even if the rows that are next to each others aren't necessarily odd and even?

Answer

Tadeck picture Tadeck · Jun 2, 2011

If you are using jQuery, you can employ one of its functions, for example .filter(), to choose only the elements that are visible. But the key here is a CSS selector :visible.

For example (see jsfiddle):

jQuery('tr:visible:odd').css({'background-color': 'red'});
jQuery('tr:visible:even').css({'background-color': 'yellow'});