如何定位<table#id>中的第一个<tr>,而不是<td> <table> <td>中的第一个<tr>

时间:2019-09-24 18:22:28

标签: html css

表“ tabid”的第一行已按预期选择。但是,第二个表的第一行也被选中,我不希望这样做。

table#tabid tr:first-of-type {
  background-color: yellow;
}
<table id="tabid">
  <tbody>
    <tr>
      <td>Select me</td>
      <td>cell-112</td>
      <td>cell-113</td>
    </tr>
    <tr>
      <td>cell-121</td>
      <td>cell-122</td>
      <td>cell-123</td>
    </tr>
    <tr>
      <td>cell-131</td>
      <td>Cell-132</td>
      <td>Cell-133</td>
    </tr>
    <tr>
      <td>
        <table>
          <tbody>
            <tr>
              <td>, but not me</td>
              <td>cell-141-1</td>
              <td>cell-141-1</td>
              <td>cell-141-1</td>
            </tr>
          </tbody>
        </table>
      </td>
      <td>cell-142</td>
      <td>cell-143</td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:2)

您可以像这样使用child combinator>

table#tabid > tbody > tr:first-of-type {
  background-color: yellow;
}

table#tabid > tbody > tr:first-of-type {
  background-color: yellow;
}
<table id="tabid">
  <tbody>
    <tr>
      <td>Select me</td>
      <td>cell-112</td>
      <td>cell-113</td>
    </tr>
    <tr>
      <td>cell-121</td>
      <td>cell-122</td>
      <td>cell-123</td>
    </tr>
    <tr>
      <td>cell-131</td>
      <td>Cell-132</td>
      <td>Cell-133</td>
    </tr>
    <tr>
      <td>
        <table>
          <tbody>
            <tr>
              <td>, but not me</td>
              <td>cell-141-1</td>
              <td>cell-141-1</td>
              <td>cell-141-1</td>
            </tr>
          </tbody>
        </table>
      </td>
      <td>cell-142</td>
      <td>cell-143</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:1)

使用子选择器>

table#tabid > tbody > tr:first-of-type {
    background-color: yellow;
}

结果

table#tabid>tbody>tr:first-of-type {
  background-color: yellow;
}
<table id="tabid">
  <tbody>
    <tr>
      <td>Select me</td>
      <td>cell-112</td>
      <td>cell-113</td>
    </tr>
    <tr>
      <td>cell-121</td>
      <td>cell-122</td>
      <td>cell-123</td>
    </tr>
    <tr>
      <td>cell-131</td>
      <td>Cell-132</td>
      <td>Cell-133</td>
    </tr>
    <tr>
      <td>
        <table>
          <tbody>
            <tr>
              <td>, but not me</td>
              <td>cell-141-1</td>
              <td>cell-141-1</td>
              <td>cell-141-1</td>
            </tr>
          </tbody>
        </table>
      </td>
      <td>cell-142</td>
      <td>cell-143</td>
    </tr>
  </tbody>
</table>

enter image description here