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

为何Bootstrap中:active伪类背景色不生效?文本颜色却正常

Bootstrap按钮:active伪类背景色不生效问题

使用Bootstrap开发时,给按钮添加:active伪类样式,文本颜色可正常改变,但背景色无法显示。

相关代码

HTML

<button class="btn btn_style">1</button>
<button class="btn btn_style">2</button>
<button class="btn btn_style">3</button>
<button class="btn btn_style">4</button>
<button class="btn btn_style">5</button>

CSS

.btn_style {
    background-color: hsl(216, 12%, 8%);
    color: hsl(217, 12%, 63%);
    border-radius: 50%;
    height: 3rem;
    width: 3rem;
}

.btn_style:hover, .submit_btn {
    background-color: hsl(25, 97%, 53%);
    color: #fff;
}

.btn_style:active {
    border: none;
    background-color: hsl(217, 12%, 63%);
    color: #fff;
}

期望效果

:active状态下:

background-color: hsl(217, 12%, 63%);
color: #fff;

解决方案

问题出在CSS优先级冲突:Bootstrap自带的.btn:active样式优先级与你自定义的.btn_style:active相同,如果Bootstrap样式在你的自定义样式之后加载,就会覆盖你的背景色设置。

解决方法是提高自定义:active样式的优先级,推荐使用组合选择器:

/* 用.btn和.btn_style组合选择器,提升权重 */
.btn.btn_style:active {
    border: none;
    background-color: hsl(217, 12%, 63%);
    color: #fff;
}

这样选择器的权重从单个类的10提升到两个类的20,能够覆盖Bootstrap默认的.btn:active样式,背景色就能正常显示了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:10:30