21

How would I create an HTML text box that exactly 3 characters can fit into it?
I found this online: <input type="text" style="width: 10px; padding: 2px; border: 1px solid black"/>
It creates a text box with width of 10px. I could use this but I was wondering if we could explicitely set for 3 chars width instead of "playing" with pixels,

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • 1
    Some interesting discussion about this [here](http://stackoverflow.com/q/1480588/589985) - the `size` attribute should work, but it'll be overridden by any CSS that might apply. And it may not be consistent across browsers... – Xavier Holt Jun 02 '13 at 20:01
  • @XavierHolt:`size` is for the max acceptable input. I am interested in width – Cratylus Jun 02 '13 at 20:02
  • 3
    @Craytus - Actually, `size` affects width here - `maxlength` is the one that controls the max number of characters. Check out [this page](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input) for a more thorough description. – Xavier Holt Jun 02 '13 at 20:04

2 Answers2

16

Use the ch metric.

width: 3ch;

Make sure your box-sizing property is set to content-box if you're changing left and/or right padding.

Kerry Johnson
  • 842
  • 9
  • 16
11

Not reliably, since l and W have very different widths.

However, if you set the font to monospace, that helps. Then, you should be able to set size="3" on the input element, and in theory it should be exactly three characters wide.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    This generally works in practice, too. And the font does not need to be set to `monospace` (the browser-dependent generic monospace font) but to *some* monospace font, e.g. with `font-family: Consolas, Lucida Console, monospace`. – Jukka K. Korpela Jun 02 '13 at 21:00