通过col类和td类定位特定的td?

时间:2016-11-21 05:44:42

标签: html css css-selectors

.col2 .positive {
  background:green;
}
.col2.positive {
  background:green;
}

.col3 .positive {
  background:blue;
}
td{
  border:1px solid blue;
  padding:5px;
}
<table>
  <col class="col1" />
  <col class="col2" />
  <col class="col3" />
  <tbody>
    <tr>
      <td></td>
      <td class="positive"></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td class="negative"></td>
      <td class="positive"></td>
    </tr>
    <tr>
      <td></td>
      <td class="positive"></td>
      <td></td>
    </tr>
  </tbody>
</table>

鉴于上面的HTML,如何在CSS中选择col2中的所有正值?我用过这个但是没用。

怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用td:nth-child(2).positive

这将选择具有类td的第二个positive元素。

tr td:nth-child(2).positive {
  background: green;
}
<table>
  <col class="col1" />
  <col class="col2" />
  <col class="col3" />
  <tbody>
    <tr>
      <td>1</td>
      <td class="positive">2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>1</td>
      <td class="negative">2</td>
      <td class="positive">3</td>
    </tr>
    <tr>
      <td>1</td>
      <td class="positive">2</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:1)

您可以使用nth-child css选择器。

这是你能做的。

tbody td:nth-child(2).positive {
  background: green;
}
tbody td:nth-child(2).positive {
  background: green;
}
tbody td:nth-child(3).positive {
  background: blue;
}
<table>
  <col class="col1" />
  <col class="col2" />
  <col class="col3" />
  <tbody>
    <tr>
      <td></td>
      <td class="positive">Positive</td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td class="negative">Negative</td>
      <td class="positive">Positive</td>
    </tr>
    <tr>
      <td></td>
      <td class="positive">Positive</td>
      <td></td>
    </tr>
  </tbody>
</table>

答案 2 :(得分:0)

&#13;
&#13;
tbody td:nth-child(2).positive {
   background: green;
}
tbody td:nth-child(3).positive {
   background: blue;
}
td{
  border:1px solid blue;
  padding:5px;
}
&#13;
<table>
  <col class="col1" />
  <col class="col2" />
  <col class="col3" />
  <tbody>
    <tr>
      <td></td>
      <td class="positive"></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td class="negative"></td>
      <td class="positive"></td>
    </tr>
    <tr>
      <td></td>
      <td class="positive"></td>
      <td></td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;