I have been playing around with the :has
selector to see if I am able to create a pure-css solution for highlighting rows in “tree” views using HTML table. I’ve seen solutions using <tbody>
, but that will only work for a single level of “nesting.” How do we handle multiple <th>
elements in the same row, and across rows that have varying rowspan
values?
I come up with something that works, but requires a selector for every possible value of rowspan
that could appear in the table. You can imagine if these tables are dynamically generated, this would not be a solution that could scale.
I wanted to see if anyone else has solved this problem using modern CSS, or could think of a way to iterate on this solution to not need to have a rule per rowspan
value.
body {
padding: 50px;
}
table {
width: 100%;
border-collapse: collapse;
}
td,
th {
padding: 20px;
border: 1px solid black;
}
tr:hover th,
tr:hover td,
tr:has(th[rowspan]):has(~ tr:hover) th[rowspan] {
background-color: aqua;
}
tr:has(th[rowspan="2"]):has(+ tr ~ tr:hover) th[rowspan="2"],
tr:has(th[rowspan="3"]):has(+ tr + tr ~ tr:hover) th[rowspan="3"],
tr:has(th[rowspan="4"]):has(+ tr + tr + tr ~ tr:hover) th[rowspan="4"],
tr:has(th[rowspan="5"]):has(+ tr + tr + tr + tr ~ tr:hover) th[rowspan="5"],
tr:has(th[rowspan="6"]):has(+ tr + tr + tr + tr + tr ~ tr:hover) th[rowspan="6"],
tr:has(th[rowspan="7"]):has(+ tr + tr + tr + tr + tr + tr ~ tr:hover) th[rowspan="7"],
tr:has(th[rowspan="8"]):has(+ tr + tr + tr + tr + tr + tr + tr ~ tr:hover) th[rowspan="8"],
tr:has(th[rowspan="9"]):has(+ tr + tr + tr + tr + tr + tr + tr + tr ~ tr:hover) th[rowspan="9"] {
background-color: inherit;
}
<table>
<tbody>
<tr>
<th rowspan="5"></th>
<th rowspan="2"></th>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th rowspan="3"></th>
<th rowspan="2"></th>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th rowspan="9"></th>
<th rowspan="4"></th>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th rowspan="2"></th>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<th rowspan="5"></th>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th rowspan="3"></th>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Owen Hancock is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.