如何突出显示两个表行,其中一行包含具有“ rowspan”属性的单元格?

时间:2018-09-29 07:51:45

标签: html css

这是表格的样子:

table {
  border-collapse: collapse;
}
<table border="1">
  <tr>
    <td rowspan="2">Text here</td>
    <td>The row 1 text goes here</td>
  </tr>
  <tr>
    <td>The row 2 text goes here</td>
  </tr>
  <tr>
    <td rowspan="2">Text here</td>
    <td>The row 1 text goes here</td>
  </tr>
  <tr>
    <td>The row 2 text goes here</td>
  </tr>
  <tr>
    <td rowspan="2">Text here</td>
    <td>The row 1 text goes here</td>
  </tr>
  <tr>
    <td>The row 2 text goes here</td>
  </tr>
</table>

我想要实现的是,当用户将鼠标悬停在其中一行上时,相邻的另一行以及用户所悬停的行都将突出显示。我尝试过:

table {
  border-collapse: collapse;
}

table tr:nth-child(odd):hover {
  background: #CCC;
}

table tr:nth-child(odd):hover + tr {
  background: #CCC;
}

table tr:nth-child(even):hover {
  background: #CCC;
}
<table border="1">
  <tr>
    <td rowspan="2">Text here</td>
    <td>The row 1 text goes here</td>
  </tr>
  <tr>
    <td>The row 2 text goes here</td>
  </tr>
  <tr>
    <td rowspan="2">Text here</td>
    <td>The row 1 text goes here</td>
  </tr>
  <tr>
    <td>The row 2 text goes here</td>
  </tr>
  <tr>
    <td rowspan="2">Text here</td>
    <td>The row 1 text goes here</td>
  </tr>
  <tr>
    <td>The row 2 text goes here</td>
  </tr>
</table>

这几乎可以用,但是当您将鼠标悬停在显示为“第2行文本在此处”的行上时,只会突出显示该行。是否有针对此问题的仅HTML / CSS解决方法?

我在想的是类似<rowgroup>的东西。

1 个答案:

答案 0 :(得分:4)

tbody标签是一个组,您可以使用它multiple times

table {
  border-collapse: collapse;
}

tbody:hover {
  background: #CCC;
}
<table border="1">
  <tbody>
    <tr>
      <td rowspan="2">Text here</td>
      <td>The row 1 text goes here</td>
    </tr>
    <tr>
      <td>The row 2 text goes here</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td rowspan="2">Text here</td>
      <td>The row 1 text goes here</td>
    </tr>
    <tr>
      <td>The row 2 text goes here</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td rowspan="2">Text here</td>
      <td>The row 1 text goes here</td>
    </tr>
    <tr>
      <td>The row 2 text goes here</td>
    </tr>
  </tbody>
</table>