tsh
tsh

Reputation: 4738

css selector for first row in a table

I need a css selector for first <tr> in a <table>.

I had searched on the internet and got some selectors like tr:first-child table *:first-child tr:first-child, table tr:first-child. But they do not works on my situation...

Here is a piece of HTML code which need to handle:

<table>
  <thead>
    <tr><th>you should chose this row</th></tr>
    <tr><th>not this one</th></tr>
  </thead>
  <tbody>
    <tr><td>not this one</td></tr>
  </tbody>
</table>


<table>
  <colgroup>
    <col></col>
  </colgroup>
  <thead>
    <tr><th>you should chose this row</th></tr>
    <tr><th>not this one</th></tr>
  </thead>
  <tbody>
    <tr><td>not this line</td></tr>
  </tbody>
</table>


<table>
  <colgroup>
    <col></col>
  </colgroup>
  <tbody>
    <tr><td>you should chose this row</td></tr>
    <tr><th>not this one</th></tr>
  </tbody>
</table>

(prefer a solution without javascript)

Upvotes: 6

Views: 18564

Answers (3)

Stefan Vilbrandt
Stefan Vilbrandt

Reputation: 292

table tr:first-of-type

should work. First-child is often missunderstood. It doesn´t care much about the element before the ":", it only looking "what is the first child of that element?". If it happend to be the same as before the ":", everything is fine. But if not, like in your case, nothing happens. So, in most case is more useful to write something like

table > :first-child

That wouldn´t help in your case here, but is the best way to use :first-child (or *-child in general) i think. If you want to get the first appearance of a element, :first-type is your answer.

Update I saw that point in another questions: If you don´t want the rows of the thead, you need to use tbody as parent element of course.

tbody tr:first-of-type

or

tbody > :first-child

Upvotes: 3

BoltClock
BoltClock

Reputation: 723408

If the first row group in your table is either a thead or a tbody, and assuming the only children your table will have are colgroup, thead and tbody:

thead:first-child > tr:first-child,
tbody:first-child > tr:first-child,
colgroup + thead > tr:first-child,
colgroup + tbody > tr:first-child

(If the first row group may instead be a tfoot, add the appropriate selectors to the list. Either way, you need all of them in order to cover all the bases.)

Upvotes: 3

pwolaq
pwolaq

Reputation: 6381

there isn't any selector that would work for you without adding some classes to distinguish different cases

thead tr:first-child would work for first two examples, but it would fail in the 3rd

EDIT: you could also try something like this:

thead tr:first-child,
tbody tr:first-child {
    /* your css styles */
}

thead + tbody tr:first-child {
    /* reset css from previous selector */
}

but if I were you I'd avoid doing that

Upvotes: 4

Related Questions