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?
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'});
Since the "missing stripe phenomenon" only occurs if an odd number of rows is hidden, you might get away with adding a single invisible padding row wherever an odd number of rows is hidden.
Row 1 Row 2 Row 3 (hidden) Padding (hidden) Row 4 Row 5
If this actually is a good solution highly depends on your current code, e.g. how you create the table and how rows are hidden.
But if your tables are huge and large chunks of consecutive rows are hidden, this would perform much better than a Javascript/jQuery solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With