使用first-child的CSS伪选择器

Nei*_*eil 2 css css-selectors

我知道我可以通过指定一个id但我想用伪选择器练习来轻松完成.

我在视图中有两个表.使用伪选择器:

  • 我只想抓住第一张桌子.
    • 在第一张表中 <tbody>
      • 我想抓住第一个 <tr>并将所有文本的颜色都染成红色.

我目前的实施几乎可行.问题是它为视图中的每个表执行此样式.我希望这种样式发生在第一个表中.

tbody tr:first-child {
  color: red; 
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Ser*_* Tx 5

为表使用另一个伪选择器:

table:nth-of-type(1) tbody tr:first-child {
  color: red; 
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)