I have a simple table structure
<table class="striped">
<tr class="parent"><td></td></tr>
<tr class="parent"><td></td></tr>
<tr class="parent"><td></td></tr>
<tr class="parent"><td></td></tr>
</table>
I can easily add CSS:
.striped tbody tr.parent:nth-of-type(odd) { background:red; }
The trouble is when you click one of these parent <tr>
rows it will expand and add an additional <tr>
detail row such as below:
<table class="striped">
<tr class="parent"><td></td></tr>
**<tr class="detail"><td></td></tr>**
<tr class="parent"><td></td></tr>
<tr class="parent"><td></td></tr>
<tr class="parent"><td></td></tr>
</table>
Is there a pure CSS way to keep just the original striping? Here is a codepen to show what is happening to the two tables
If you have the option of changing the HTML slightly, you could use multiple explicit <tbody>
elements and insert the child element inside the same <tbody>
as the parent. This actually makes semantic sense as well as it groups the parent with its child.
From https://developer.mozilla.org/en/docs/Web/HTML/Element/tbody
multiple
<tbody>
elements are permitted (if consecutive), allowing the data-rows in long tables to be divided into different sections, each separately formatted as needed
E.g.
.striped tbody:nth-of-type(odd) .parent { background:red; }
<table class="striped">
<tbody>
<tr class="parent"><td>Stuff</td></tr>
<tr class="child"><td>child</td></tr>
</tbody>
<tbody><tr class="parent"><td>Stuff</td></tr></tbody>
<tbody><tr class="parent"><td>Stuff</td></tr></tbody>
<tbody><tr class="parent"><td>Stuff</td></tr></tbody>
</table>
Is there only going to be one single .detail
element at any given time?
If so, you could “reset” the background for the TR following that element, like this:
.striped tbody tr.parent:nth-of-type(odd) { background:red; }
.striped tbody tr.detail ~ tr.parent:nth-of-type(even) { background:red; }
.striped tbody tr.detail ~ tr.parent:nth-of-type(odd) { background:none; }
<table class="striped">
<tr class="parent"><td>A</td></tr>
<tr class="detail"><td>inserted</td></tr>
<tr class="parent"><td>B</td></tr>
<tr class="parent"><td>C</td></tr>
<tr class="parent"><td>D</td></tr>
<tr class="parent"><td>E</td></tr>
<tr class="parent"><td>F</td></tr>
<tr class="parent"><td>G</td></tr>
</table>
Since this inserted table row changes the “index” of all following TR by one, making the even ones following this details rows have a red background will continue the striping in the “right” way. (And the background for following odd rows has to be “nulled”, otherwise those would still have a red background from the first rule.)
Of course, as soon as you might have more than one .detail
row inserted into the table, it won’t work that simple any more.
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