Size attribute for an input field not being honored

Doug Chamberlain picture Doug Chamberlain · Jul 14, 2011 · Viewed 38.2k times · Source

Taken directly from W3Schools:

Definition and Usage The size attribute specifies the width of an input field.

For <input type="text"> and <input type="password">, the size attribute defines the number of characters that should be visible. For all other input types, size defines the width of the input field in pixels.

So..

If that is true why is my field <input type="text" size="2"/> wide enough to display 5 CAPTIAL MMMMM's ?

Answer

Gaurav picture Gaurav · Jul 14, 2011

The same "erroneous" information is specified in the HTML4 Spec, the HTML5 spec, Sitepoint, Mozilla Developer Network, and Microsoft's MSDN library. So it isn't just W3Schools' fault.

Anyway, while the specs say that the size attribute should be the number of characters visible, most web browsers have settled on using the number of em units, meaning the width of the character of the capital M.

To specify the width precisely in pixels, or any unit of your choice, use the CSS width property.

To answer your updated question: it's the width of the capital M in the default font size as applied by CSS styling to the text box, but the font size of the text inside the text box is usually smaller.

Want to make a set number of characters fit inside the box? You'll have to switch to a fixed width font.