How can I add a background-color to every second table row even some table rows are not displayed?
In my HTML is a simple table with some table rows. Just like that:
<label for="cb">hide blue</label>
<input id="cb" type="checkbox" onchange="hideBlue(this.checked)" />
<table>
<tr data-cat="red">
<td>red car</td>
</tr>
<tr data-cat="blue">
<td>blue jacket</td>
</tr>
<tr data-cat="red">
<td>red bull</td>
</tr>
<tr data-cat="red">
<td>red pen</td>
</tr>
</table>
As you can see there is also a checkbox which can toggle the "blue" category-rows. My CSS is looking like that:
tr:nth-child(odd) {
background-color:#aaa;
}
But now if someone hides the "blue" category (by adding a display:none
-class), the background colors are not alternate right anymore.
How can I prevent this failure?
I already tried to add :not(.displaynone)
to the css rule but this didn't work.
Here is a jsFiddle
There is a way to get the updating alternating row colors using only CSS selectors.
tr:nth-child(odd) {
background-color:#aaa;
}
tr.displaynone ~ tr {
background-color: transparent;
}
tr.displaynone ~ tr:nth-child(even) {
background-color:#aaa;
}
What this does is it sets all siblings after the displaynone
row background-color
to transparent
, and then sets the even rows after that background-color
to #aaa
.
This works for your example fiddle (forked here), but it will not work if you have to hide more than one element at once. (example, comment out the marked line and click on rows).
If you need to hide multiple rows at once, this solution will not work for you, and you'd have to use javascript to compute the row color whenever you hide/show rows.
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