You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为CSS类设置样式:让首个active类td变红、第二个变黄

实现目标样式的两种方案

要给页面中第一个带有active类的<td>设置红色背景,第二个设置黄色背景,可根据兼容性需求选择以下方案:

方案一:使用现代CSS选择器(推荐,支持Chrome 111+、Firefox 113+等)

利用CSS Selectors Level 4新增的:nth-of()选择器,直接匹配所有带有active类的<td>中的第1个和第2个元素,无需依赖HTML结构:

/* 第一个带有active类的<td> */
td.active:nth-of(1) {
  background: red;
}

/* 第二个带有active类的<td> */
td.active:nth-of(2) {
  background: yellow;
}

方案二:基于HTML结构的兼容方案(适配旧浏览器)

如果需要兼容不支持:nth-of()的旧浏览器,可通过定位<tr>的位置精准选中目标<td>(前提是HTML结构固定):

/* 第二个<tr>中的.active<td>(即第一个active元素) */
table tr:nth-child(2) td.active {
  background: red;
}

/* 第三个<tr>中的.active<td>(即第二个active元素) */
table tr:nth-child(3) td.active {
  background: yellow;
}

完整代码示例

HTML(保持原结构不变)

<div class="wrapper">
   <table>
     <tr>
       <td class="cell">1</td>
       <td class="cell">2</td>
       <td class="cell">3</td>
     </tr>
     <tr>
       <td class="cell active">4</td>
       <td class="cell in-range">5</td>
       <td class="cell in-range">6</td>
     </tr>
     <tr>
       <td class="cell in-range">7</td>
       <td class="cell active">8</td>
       <td class="cell">9</td>
     </tr>
   </table>
</div>

内容的提问来源于stack exchange,提问作者TheTarasik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:05:22