13

I have a number input in html. I want to center the text (i.e. the input) that is inside. I of course did:

text-align: center;

which sort of works. The problem is though. The text is now centered when those arrows are shown. But when the arrows disappear, the text stays at the same position which now of course isn't the center anymore.

Without arrows, the text does not appear centered.

tomet
  • 2,416
  • 6
  • 30
  • 45
  • set arrows as backgrounds? maybe? - We need code (tryout codepen.io or jsfiddle.net) – Jack May 18 '14 at 00:31

4 Answers4

29

You can have the spinner buttons (arrows) always show:

input[type='number']::-webkit-inner-spin-button, 
input[type='number']::-webkit-outer-spin-button { 
    opacity: 1;
}

Or you can have them always hidden:

input[type='number']::-webkit-inner-spin-button, 
input[type='number']::-webkit-outer-spin-button { 
    -webkit-appearance: none;
    margin: 0;
}

With either option, the contents will always be centred.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • do we need moz or ms as well? – emil Jan 25 '18 at 14:23
  • 1
    @emil Edge uses `-webkit` so there's no `-ms` equivalent. For moz you can try adjusting the [`-moz-appearance`](https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-appearance) property. Also see https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-inner-spin-button – rink.attendant.6 Jan 25 '18 at 19:18
3

I found that playing around with the width and padding-left properties worked in my situation because I required a fairly small box of width 45px.

So using

padding-left:10px;
width:45px;
text-align:center;

worked nicely.

https://jsfiddle.net/faanvme3/

Andy
  • 2,124
  • 1
  • 26
  • 29
1

Just this if you are using bootstrap:

Using css

input[type="number"] {
  text-align: center;
}

Using bootstrap

<input type="number" class="text-center" min="1" max="99" name="quantity">
kib gabriel
  • 108
  • 7
1

I achieved what you describe using position relative/absolute on the spinner. The outcome is that the text of your input is centred while keeping the convenience of the spinner on top of it when necessary.

    input {
    text-align: center;
    position: relative;
  }
  input[type='number']::-webkit-inner-spin-button {
    position: absolute;
    width: 12.5%;
    height: 100%;
    top: 0;
    right: 0;
  }

In this example I assumed the spinner would be 1/8 of the size of the input, but that's up to you.

Cactus
  • 175
  • 2
  • 12