Reputation: 6347
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 some margin) as 1 size 60 field. However, in Internet Explorer the two fields are much bigger than the one field.
On another row I have 3 fields, 2 of a 12 size, and 1 of a 28 size. After removing all borders/paddings/margins from the fields, I have the following, and don't understand why:
1 field of size 60 = 327px width
2 fields, 12 & 44 size (56 total size) = 87px & 247px width (334px total width)
3 fields, 12, 12 & 28 size (52 total size) = 87px, 87px & 167px width (341px total width)
Why does it work that way in IE, but differently in other browsers? And is there a way to make it work consistently, using only CSS? (I do not have easy access to other ways. I'm well aware that there are better ways though)
Upvotes: 0
Views: 1878
Reputation: 201896
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
.)
Upvotes: 4