使用 first-child 的 CSS 伪选择器

标签 css css-selectors

我知道我可以通过指定 id 轻松做到这一点但我想练习伪选择器。

我在一个 View 中有两个表。使用伪选择器:

  • 我只想抢第一张 table 。
    • 在第一个表的 <tbody>
      • 我想抢第一个 <tr>并将所有文本涂成红色。

我目前的实现几乎可以正常工作。问题是它对 View 中的每个 表都进行了这种样式设置。我希望这种样式出现在第一个表中。

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>

最佳答案

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

table:nth-of-type(1) 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>

关于使用 first-child 的 CSS 伪选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39083397/

相关文章:

css - 背景大小为 'changing image link/on hover' + 文本定位的问题

jquery - 使用 jquery 更改背景图像

css - 如何设置 html5 日期输入的样式,第一个元素 focus/active

html - 第 n 个类型的选择器未按预期工作

javascript - 可见绑定(bind)和动态 css 绑定(bind)

jquery - 动态 CSS 宽度

css - 如何正确循环 nth-of-type?

CSS >(选择器)不工作

css - 带有菜单的响应式 Logo 定位

html - CSS - 只有类型选择器没有正确应用