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

如何为HTML计算器中数字25的按钮设置颜色(参考15按钮样式)

解决计算器按钮25样式匹配15的问题

问题分析

当前代码中,数字15的按钮通过以下CSS规则设置了红色背景及点击态颜色:

.keypad :last-child :nth-child(3){
background-color: #b22222;}

.keypad :last-child :nth-child(3):active{
background-color: #801818;}

而数字25的按钮位于**第二个.keys-row**的第二个位置,需要针对这个特定位置编写CSS选择器,才能覆盖默认的按钮样式。

解决方案

在现有<style>标签中添加以下规则,即可让25按钮的颜色和15按钮完全一致:

/* 设置25按钮的默认背景色 */
.keypad .keys-row:nth-child(2) .key:nth-child(2) {
  background-color: #b22222;
}

/* 设置25按钮点击时的背景色 */
.keypad .keys-row:nth-child(2) .key:nth-child(2):active {
  background-color: #801818;
}

完整修改后代码

<div class="calc">
<div id="display" class="display">0</div>
<div class="keypad">

<div class="keys-row first-keys-row">
<div class="key clear-all">AC</div>
<div class="key show-display">80</div>
<div class="key show-display">85</div>
<div class="key show-display">90</div></div>

<div class="keys-row">
<div class="key show-display">20</div>
<div class="key show-display">25</div>
<div class="key show-display">30</div>
<div class="key show-display">35</div></div>

<div class="keys-row">
<div class="key show-display">5</div>
<div class="key show-display">10</div>
<div class="key show-display">15</div>
<div class="key calculate">=</div></div></div></div>

<style>
.calc {
color: #fff;
width: 400px;
padding: 10px;
background-color: #302d2d;
border: 10px solid #302d2d;
border-bottom: 5px solid #302d2d;
border-radius: 10px;
margin-left: 10px;}

.calc .display {
font-size: 40px;
margin-bottom: 20px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
background-color: gray;
border: 10px solid gray;
border-radius: 10px;
color: black;
height: 80px;}

.keys-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;}

.keypad .keys-row .key {
background-color: #999191;
font-size: 35px;
text-align: center;
width: 95px;
line-height: 75px;
border-radius: 50px;
margin: 0 5px;
cursor: pointer;
user-select: none;}

.keypad :first-child :nth-child(1){
background-color: black;}

.keypad .keys-row .key:active{
background-color: #a5a5a590;}

.keypad :last-child :nth-child(4){
background-color: lightseagreen;}

.keypad :last-child :nth-child(4):active{
background-color: #17807a;}

.keypad :last-child :nth-child(3){
background-color: #b22222;}

.keypad :last-child :nth-child(3):active{
background-color: #801818;}

/* 新增25按钮样式 */
.keypad .keys-row:nth-child(2) .key:nth-child(2) {
  background-color: #b22222;
}

.keypad .keys-row:nth-child(2) .key:nth-child(2):active {
  background-color: #801818;
}
</style>

规则说明

  • .keys-row:nth-child(2)精准选中.keypad下的第二行(包含20、25的行)
  • .key:nth-child(2)选中该行内的第二个按钮(即显示25的按钮)
  • 新增规则的优先级高于默认按钮样式,确保颜色能正确覆盖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:31:37