为何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
相关产品推荐
相关产品推荐

