How to select the immediate rows of a table using CSS

Viewed 48

In CSS, we can specify this style against the immediate child rows of a table:

table > tr {
    background: blue;
}

That will not work if we have a <tbody> tag around the <tr> tags.

Is there a way to cover both cases without having to do this:

table > tr, table > tbody > tr {
    background: blue;
}

We cannot do this also as it will impact grandchildren rows down the tree:

table tr {
    background: blue;
}
2 Answers

There is no syntax for a "depth range" in CSS, so this way or another you would need to implicitly account for both situations.

You said you want to avoid

table > tr, table > tbody > tr {

though it's not that long. But the following alternatives would do too:

table > tr, tbody > tr {


:is(table, tbody) > tr {


:where(table, tbody) > tr {

If the table has a class my-table

:where(.my-table, .my-table > tbody) > tr {

You can select any rows you like, by adding a class to them, and creating css styles for this class.

HTML:

<tr class="superrow">
  ...
</tr>

CSS:

.superrow { background: blue; }
Related