当tbody悬停时覆盖元素的样式

时间:2017-01-19 21:22:10

标签: html css

我在:hover中遇到了问题。

我希望tr的{​​{1}}的最后tbody在其tbody悬停时也会改变颜色。问题是最后一个tr有自己的类。

这是我的代码的结构:

.cust-table {
  border: 1px solid black;  
  border-collapse: collapse;
  width: 100%;
}

.cust-table td {
  border: 1px solid black;
  padding: 10px;
}

.cust-table tbody:nth-child(even){
  background-color: white;
}

.cust-table tbody:nth-child(odd){
  background-color: green;
}

.cust-color {
  background-color: blue; 
}

.cust-table tbody:hover {
  background-color: yellow;
}
<table class="cust-table">
  <tbody>
    <tr>
      <td rowspan="2">A</td>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr class="cust-color">
      <td  colspan="3">Cust color</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td rowspan="2">B</td>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr class="cust-color">
      <td  colspan="3">Cust color</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td rowspan="2">C</td>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr class="cust-color">
      <td  colspan="3">Cust color</td>
    </tr>
  </tbody>
</table>

我尝试添加cust-color:hover,但正如预期的那样,它仅在<tr>cust-color悬停时才有效。

3 个答案:

答案 0 :(得分:3)

仅当tbody未悬停时才使用此规则设置自定义颜色:

tbody:not(:hover) .cust-color {
  background-color: blue; 
}

&#13;
&#13;
.cust-table {
  border: 1px solid black;  
  border-collapse: collapse;
  width: 100%;
}

.cust-table td {
  border: 1px solid black;
  padding: 10px;
}

.cust-table tbody:nth-child(even){
  background-color: white;
}

.cust-table tbody:nth-child(odd){
  background-color: green;
}

tbody:not(:hover) .cust-color {
  background-color: blue; 
}

.cust-table tbody:hover {
  background-color: yellow;
}
&#13;
<table class="cust-table">
  <tbody>
    <tr>
      <td rowspan="2">A</td>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr class="cust-color">
      <td  colspan="3">Cust color</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td rowspan="2">B</td>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr class="cust-color">
      <td  colspan="3">Cust color</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td rowspan="2">C</td>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr class="cust-color">
      <td  colspan="3">Cust color</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Ori Drori的回答可能是最好的,但这是另一种解决方案:

.cust-table tbody:hover, .cust-table tbody:hover tr.cust-color {
  background-color: yellow;
}

当其父tbody悬停时覆盖tr颜色。

答案 2 :(得分:1)

为特定的tr添加规则:

.cust-table tbody:hover,
.cust-table tbody:hover .cust-color{
   background-color: yellow;
}