Skip to content Skip to sidebar Skip to footer

Cross Browser Setting Input "size"-attribute

Can anyone explain to me how the 'size'-attribute of input fields works? In reasonable browsers (like Chrome) I managed to make a size 12 and a size 44 field just as wide (with som

Solution 1:

According to HTML5, the size attribute specifies “the number of characters that, in a visual rendering, the user agent is to allow the user to see while editing the element's value”. This is a somewhat unfortunate formulation and does not correspond to reality. The description in HTML 3.2 is more realistic: “Used to set the visible size of text fields to a given number of average character widths”. The concept of “average character width” is very vague, and browsers interpret it differently.

Thus, the actual effect of a size attribute depends, in addition to its value of course, on the font face and size and on the browser. There is considerable variation. Moreover, if you have two input elements in succession, on the same line, the total width occupied also depends on the spacing (if any) between the elements.

If you want to have, say, two input fields touching each other and a third input field below them so that it occupies exactly the same width as the two combined, then you should set their width properties in CSS and set the box model so that the width includes padding and border. Example:

<style>
input { box-sizing: border-box }
</style>
<input style="width: 12ch"><input style="width: 44ch"><br>
<input style="width: 56ch">

If you need to worry about old browsers that do not support the ch unit, use the em unit (which corresponds to about 2 times the width of an “average” character, very roughly speaking):

<style>
input { box-sizing: border-box }
</style>
<input style="width: 6em"><input style="width: 22em"><br>
<input style="width: 28em">

(You can also combine the use of units, using em as the fallback unit, e.g. width: 6em; width: 12ch.)


Post a Comment for "Cross Browser Setting Input "size"-attribute"