Home > Software engineering >  CSS - Select either first row or head row in HTML Table
CSS - Select either first row or head row in HTML Table

Time:09-10

I have a mixed set of tables on the website. Some have the thead present and others directly start with a tr without having thead.

Since I want the first row to become sticky and scroll with the user till last row in the table, I added the following code:

.wp-block-table tr:first-child {
  left: 0;
    position: sticky;
    top: 0;
    z-index: 1;
    width: 25vw;
    background: white;
}

But the issue now is that the table without thead scrolls but when a table has thead present then the scroll starts from the second row (i.e after skipping the thead)

I know I need to fix the table HTML so that they are consistent everywhere but in the meantime is there any CSS selector which can handle the sticky scrolling in both the cases.

If thead is not present then use my above code and if thead is present then I will need to add some extra CSS code. I need help with that extra code. Never been in such a situation before.

CodePudding user response:

You can apply first-child to find the first child (thead or tbody) and the first-child inside of it to find the first tr:

table > *:first-child > tr:first-child {
    background-color: green;
}
<table>
    <thead>
        <tr><td>THEAD</td></tr>
    </thead>
    <tbody>
        <tr><td>TBODY</td></tr>
    </tbody>
</table>

----------------------------------------

<table>
    <tbody>
        <tr><td>THEAD</td></tr>
        <tr><td>TBODY</td></tr>
    </tbody>
</table>

  • Related