将CSS样式添加到表格的前三行

qaxu7uf2  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(121)

对于下面的HTML,我只想在前.gold.silver.bronze行添加一些CSS样式(记住我在代码中注解的一些特殊行为)。

<table>
  <tbody>

    <!-- 
      IMPORTANT: 
      Notice that here can appear an extra <tr class="my-rank"></tr> 
      (i.e.: if he user is logged in and he/she have a rank)
    -->

    <tr class="gold"></tr>
    <tr class="silver"></tr>
    <tr class="bronze"></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    
    <!-- 
      From this point, these <tr> elements are injected with AJAX (by a pager), 
      and the three first of ones, includes .gold, .silver and .bronze classes again.
    
      I can't remove these "repeated" classes.
    -->

    <tr class="gold"></tr>
    <tr class="silver"></tr>
    <tr class="bronze"></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>

    <!-- 
      Here is another AJAX injection block, including again undesired .gold, .silver and .bronze classes...
    -->

    <tr class="gold"></tr>
    <tr class="silver"></tr>
    <tr class="bronze"></tr>
    <tr></tr>
    ...
    ...
  </tbody>
</table>

我用':first-of-type':first-child等伪选择器尝试了几次;(也结合了:not),没有运气。
有人能给我指一下正确的方向吗?

h5qlskok

h5qlskok1#

就在发布这个问题后,我找到了一个解决方案(尽管它可能不是更优雅的解决方案):
最后,我使用了这些CSS选择器:

tr.gold:nth-child(1),
tr.gold:nth-child(2) {
  /* my custom styles  */
}

tr.silver:nth-child(2),
tr.silver:nth-child(3) {
  /* my custom styles  */
}

tr.bronze:nth-child(3),
tr.bronze:nth-child(4) {
  /* my custom styles  */
}

相关问题