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

CSS选择含.approve类的Bootstrap表格行无效,请问我的写法有误吗?

问题:Bootstrap表格含.approve元素的行无法修改背景色

我的Bootstrap表格代码如下:

<div class="table-responsive">
    <table class="table table-bordered table-striped">
        <tbody>
            <tr>
                <td align="center">
                    <div><span class="approve"></span></div>
                </td>
            </tr>
        </tbody>
    </table>
</div>

我希望当表格行包含class为.approve的span元素时修改该行背景色,尝试了两种CSS写法均未生效:

第一种写法:

.table-striped > tbody > tr:nth-child(2n+1):has(span):has(.approve) > td {
   background-color: #fff3c0;
}
.table-striped > tbody > tr:nth-child(2n):has(span):has(.approve) > td {
   background-color: #fff8d9;
}

第二种写法(移除.table-striped):

.table > tbody > tr:has(span):has(.approve) > td {
   background-color: #fff8d9;
}

请问我的CSS写法是否存在错误?


问题分析与解决方案

你的CSS写法存在两个核心问题:

  • 选择器冗余+样式优先级被覆盖:你使用:has(span):has(.approve)属于冗余写法,直接用:has(.approve)即可定位到包含目标元素的行。更关键的是,Bootstrap的.table-striped是直接给<tr>设置background-color,而你给<td>设置背景色的优先级低于<tr>的样式,导致被覆盖。
  • :has()的冗余判断:.approve本身就是span元素,无需额外判断父级是span。

正确的CSS写法

针对条纹表格(保留.table-striped)

直接给目标<tr>设置背景色,通过提高优先级覆盖Bootstrap默认样式:

/* 奇数行样式 */
.table.table-striped > tbody > tr:nth-child(2n+1):has(.approve) {
  background-color: #fff3c0;
}
/* 偶数行样式 */
.table.table-striped > tbody > tr:nth-child(2n):has(.approve) {
  background-color: #fff8d9;
}

如果上述优先级仍不够,可以临时使用!important(不推荐过度使用,但针对框架样式覆盖是可行的):

.table-striped > tbody > tr:nth-child(2n+1):has(.approve) {
  background-color: #fff3c0 !important;
}
.table-striped > tbody > tr:nth-child(2n):has(.approve) {
  background-color: #fff8d9 !important;
}

通用表格(移除.table-striped时)

.table > tbody > tr:has(.approve) {
  background-color: #fff8d9;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:33:16