Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size attribute for an input field not being honored

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 ?

like image 529
Doug Chamberlain Avatar asked Jul 14 '11 20:07

Doug Chamberlain


People also ask

What is size attribute of input?

The size attribute specifies the visible width, in characters, of an <input> element. Note: The size attribute works with the following input types: text, search, tel, url, email, and password. Tip: To specify the maximum number of characters allowed in the <input> element, use the maxlength attribute.

What does the size attribute do?

The size attribute in HTML is used to specify the initial width for the input field and a number of visible rows for the select element.


2 Answers

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.

like image 157
Gaurav Avatar answered Sep 21 '22 21:09

Gaurav


The problem is that the size = x attribute isn't in pixels... rather, it denotes the very approximate size that the <input /> element must be to hold x characters. So, for example, <input size=2 /> should display a input box that can hold 2 characters.

Unfortunately, this varies from font to font (esp. variable width fonts), and so you will likely observe that setting the size attribute to 2 will in fact render an input box with the size of 5 or something like that. If you use a monospace font, though, size=2 should render a text field that can hold exactly 2 characters... or at least get close.

However, to set the width of an <input> element in pixels, ems, etc., try using the width CSS property instead:

<input type="text" style="width:20px" /> 

The above example will make the input width exactly 20 pixels wide, excluding borders and/or padding.

like image 26
Titus Avatar answered Sep 18 '22 21:09

Titus