为表的前三行添加CSS样式

  • 本文关键字:三行 添加 CSS 样式 css
  • 更新时间 :
  • 英文 :


给定以下HTML,我想添加一些CSS样式仅到第一个.gold,.silver.bronze行,(考虑到我在代码中注释的一些特殊行为)。

<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结合),没有运气。

谁能给我指个正确的方向?

就在发布这个问题之后,我找到了一个解决方案(尽管它可能不是更优雅的解决方案):

最后,我使用了这些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  */
}

最新更新