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

如何用纯CSS自定义HTML input type number的加减按钮?

纯CSS自定义input type number的加减按钮

可以仅用纯CSS实现你要的效果,但需要针对不同浏览器的私有伪元素调整样式——因为不同浏览器对number输入框的加减按钮实现逻辑不同。以下是具体实现方案:

实现代码

HTML

<input name="tgTxt" type="number" value="36.5" max="37" step="0.5" class="custom-number-input">

CSS

/* 基础样式重置,消除默认外观 */
.custom-number-input {
  -webkit-appearance: none;
  -moz-appearance: textfield;
  appearance: none;
  width: 160px;
  padding: 0.6rem 2.2rem; /* 给左右按钮预留空间 */
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  position: relative;
}

/* 适配WebKit内核浏览器(Chrome、Safari、Edge) */
.custom-number-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0.5rem;
  border: none;
  background: transparent;
}

/* 自定义WebKit下的减号按钮 */
.custom-number-input::-webkit-inner-spin-button::before {
  content: "-";
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 100%;
  background-color: #165DFF;
  color: #fff;
  font-size: 1.2rem;
  cursor: pointer;
}

/* 自定义WebKit下的加号按钮 */
.custom-number-input::-webkit-inner-spin-button::after {
  content: "+";
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 100%;
  background-color: #FF4D4F;
  color: #fff;
  font-size: 1.2rem;
  cursor: pointer;
}

/* 适配Firefox浏览器 */
.custom-number-input::-moz-number-spin-down {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 2rem;
  border: none;
  background-color: #165DFF;
  color: #fff;
  font-size: 1.2rem;
  cursor: pointer;
}

.custom-number-input::-moz-number-spin-up {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 2rem;
  border: none;
  background-color: #FF4D4F;
  color: #fff;
  font-size: 1.2rem;
  cursor: pointer;
}

补充说明

  • 兼容性:该方案支持Chrome、Safari、Edge(WebKit内核)以及Firefox等现代主流浏览器,旧版浏览器(如IE)因不支持对应伪元素,无法实现效果。
  • 核心逻辑:通过浏览器私有伪元素定位并重构加减按钮样式,将默认上下排列的按钮调整为左右分布,同时设置各自的背景色和字号。
  • 注意事项:必须给input设置足够的左右内边距,避免输入的数字被左右按钮遮挡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:40:06