How to use nth-child for styling with a table with rowspan?

css, css-selectors, html

Solution

Unfortunately, there's no way to do this with `:nth-child()` alone, or by using CSS selectors alone for that matter. This has to do with the nature of `:nth-child()` which selects purely based on an element being the nth child of its parent, as well as with CSS's lack of a parent selector (you can't select a `tr` only if it doesn't contain a `td[rowspan]`, for example).

jQuery does have the `:has()` selector that CSS lacks, though, which you can use in conjunction with `:even` (not `:odd` as it's 0-indexed versus `:nth-child()`'s 1-index) for filtering as an alternative to CSS:

$('tr:not(:has(td[rowspan])):even')

jsFiddle preview

Problem

I have a table that has one row that uses rowspan. So, ``` <table> <tr> <td>...</td><td>...</td><td>...</td> </tr> <tr> <td rowspan="2">...</td><td>...</td><td>...</td> </tr> <tr> <td>...</td><td>...</td> </tr> <tr> <td>...</td><td>...</td><td>...</td> </tr> </table> ``` I'd like to use the nth-child pseudo-class to add a background color to every other row, but the rowspan is messing it up; it adds the background color to the row below the row with the rowspan, when in fact I'd like it to skip that row, and move onto the next. Is there a way to get nth-child to do something smart, or to use [rowspan] in the selector to get around this? So in this case, I'd like the background color to be on rows 1 and 4 but then after that on 6, 8, 10, and so on (since none of those have rowspans)? It's like if I see a rowspan, then I want nth-child to add 1 to n and then continue. Probably no solution to this, but thought I'd ask :-)

Original source

Related problems