Neil Neil - 3 months ago 14
CSS Question

CSS pseudo selectors using first-child

I know I could do this easily by specifying an

id
but I want to practice with pseudo selectors.

I have two tables within a view. Using pseudo selectors:


  • I want to grab the first table only.


    • within that first table's
      <tbody>



      • I want to grab the first
        <tr>
        and color all the text red.





My current implementation almost works. The issue is that it does this styling for every table in the view. I want this styling to happen only for the first table.



tbody tr:first-child {
color: red;
}

<table>
<thead>
<tr>
<th>First Column</th>
<th>Second Column</th>
</tr>
</thead>
<tbody>
<tr>
<td> T1 R1 Col 1</td>
<td>This row should all be red</td>
</tr>
<tr>
<td>T1 R2 Col 1</td>
<td>foobar</td>
</tr>
</tbody>
</table>

<br>

<table>
<thead>
<tr>
<th>First Column</th>
<th>Second Column</th>
</tr>
</thead>
<tbody>
<tr>
<td> T2 R1 Col 1</td>
<td>This row should NOT be red</td>
</tr>
<tr>
<td>T2 R2 Col 1</td>
<td>foobar</td>
</tr>
</tbody>
</table>




Answer

You could take it a step further with the pseudo selectors since you already know you're targeting the first table and use :first-of-type which works similarly as :nth-of-type(1)

table:first-of-type tbody tr:first-child {
  color: red; 
}
<table>
  <thead>
    <tr>
      <th>First Column</th>
      <th>Second Column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> T1 R1 Col 1</td>
      <td>This row should all be red</td>
    </tr>
    <tr>
      <td>T1 R2 Col 1</td>
      <td>foobar</td>
    </tr>
  </tbody>
</table>

<br>

<table>
  <thead>
    <tr>
      <th>First Column</th>
      <th>Second Column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> T2 R1 Col 1</td>
      <td>This row should NOT be red</td>
    </tr>
    <tr>
      <td>T2 R2 Col 1</td>
      <td>foobar</td>
    </tr>
  </tbody>
</table>
Comments