みかづきブログ・カスタム

基本的にはちょちょいのほいです。

input type="number"についている上下ボタン(スピンボタン)の見た目をCSSで調整する 1️⃣

input type="number"

数字を入力することに特化した、input type="number"ですが、デフォルトで入力値をインクリメント・デクリメントさせるボタンがついてます。



webkit系のブラウザに限られますが、実はこちらのボタン、CSSを当てることが可能です。
その名も、-webkit-inner-spin-buttonと-webkit-outer-spin-buttonです。
ただ、現状ではChromeもSafariも-webkit-inner-spin-buttonしかサポートしてないみたいです。
確かにどちらのブラウザも要素の内側にボタンが表示されますからね。

developer.mozilla.org

developer.mozilla.org

例えば、

input[type=number]::-webkit-inner-spin-button {
  display: none;
}

と書けば、スピンボタンを非表示にすることができます。
非表示ではなく見た目を調整したいという場合もあると思うのですが、僕の場合はCSSで透明にしつつ、上からpointer-events: noneの要素を乗せてます。


HTML

<div class="input-box">
  <input class="input" type="number"/>
</div>

SCSS

.input-box {
  position: absolute;
  top: 0; bottom: 0; left: 0; right: 0;
  margin: auto;
  max-width: 600px;
  width: 100%; height: 60px;

  &:before {
    position: absolute;
    top: 8px;
    right: 20px;
    color: #ECEFF1;
    font-size: 20px;
    content: "▲";
    pointer-events: none;
  }
  
  &:after {
    position: absolute;
    bottom: 8px;
    right: 20px;
    color: #ECEFF1;
    font-size: 20px;
    content: "▼";
    pointer-events: none;
  }
  
  .input {
    box-sizing: border-box;
    display: block;
    margin: 0 auto 40px;
    border: none;
    border-radius: 10px;
    padding: 20px 60px 20px 20px;
    width: 100%; height: 60px;
    font: 20px "Avenir Next";
    box-shadow: 0 0 2px rgba(0, 0, 0, .5) inset;
    -webkit-appearance: none;
    
    &:focus {
      outline: none;
    }

    &::-webkit-inner-spin-button {
      position: absolute;
      top: 0; bottom: 0;
      right: 0;
      margin: auto;
      transform: scale(5);
      transform-origin: right center;
      opacity: 0;
      cursor: pointer;
    }
    
    &::-webkit-contacts-auto-fill-button {
      opacity: 0;
    }
  }
}

しれっと書いてある、-webkit-contacts-auto-fill-buttonはmobile SafariのオートフィルアイコンにCSSを当てる擬似クラスです。
オートフィルアイコンについてはまた別の機会にまとめるかもしれません。

developer.mozilla.org