285
<input name="txtId" type="text" size="20" />

or

<input name="txtId" type="text" style="width: 150px;" />

Which one is optimal cross-browser code?

Of course it depends on requirements, but I'm curious to know how people decide and on what basis.

Mark Bell
  • 28,985
  • 26
  • 118
  • 145
rajakvk
  • 9,775
  • 17
  • 46
  • 49
  • 23
    It's usually a bad idea to use "px" on the web. You might consider using relative units instead ("em", "%", etc.). – kangax Sep 26 '09 at 20:42
  • 61
    @kangax It's just one opinion; there's no consensus regarding the usage of px – Kos Apr 15 '15 at 08:56
  • 10
    @Kos It kind of was a consensus. Not anymore (with IE and other old browsers) passing away. – kangax Apr 15 '15 at 13:37
  • 17
    @kangax I never got that memo... I use px all the time and always have. – Andrew Jan 05 '17 at 21:58

10 Answers10

216

You can use both. The css style will override the size attribute in browsers that support CSS and make the field the correct width, and for those that don't, it will fall back to the specified number of characters.

Edit: I should have mentioned that the size attribute isn't a precise method of sizing: according to the HTML specification, it should refer to the number of characters of the current font the input will be able to display at once.

However, unless the font specified is a fixed-width/monospace font, this is not a guarantee that the specified number of characters will actually be visible; in most fonts, different characters will be different widths. This question has some good answers relating to this issue.

The snippet below demonstrates both approaches.

@font-face {
    font-family: 'Diplomata';
    font-style: normal;
    font-weight: 400;
    src: local('Diplomata'), local('Diplomata-Regular'), url(https://fonts.gstatic.com/s/diplomata/v8/8UgOK_RUxkBbV-q561I6kFtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
@font-face {
    font-family: 'Open Sans Condensed';
    font-style: normal;
    font-weight: 300;
    src: local('Open Sans Condensed Light'), local('OpenSansCondensed-Light'), url(https://fonts.gstatic.com/s/opensanscondensed/v11/gk5FxslNkTTHtojXrkp-xBEur64QvLD-0IbiAdTUNXE.woff2) format('woff2');
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
p {
  margin: 0 0 10px 0;
}
input {
  font-size: 20px;
}
.narrow-font {
  font-family: 'Open Sans Condensed', sans-serif;
}
.wide-font {
  font-family: 'Diplomata', cursive;
}
.set-width {
  width: 220px;
}
<p>
  <input type="text" size="10" class="narrow-font" value="0123456789" />
</p>
<p>
  <input type="text" size="10" class="wide-font" value="0123456789" />
</p>
<p>
  <input type="text" size="10" class="narrow-font set-width" value="0123456789" />
</p>
<p>
  <input type="text" size="10" class="wide-font set-width" value="0123456789" />
</p>
Mark Bell
  • 28,985
  • 26
  • 118
  • 145
  • Most fonts are not mono-width. Regarding "the number of characters the field will be able to display at once".... Which character do you mean? – Pacerier Jan 26 '15 at 13:33
  • @Pacerier The number of characters in whichever font the input is using: http://jsbin.com/zimako/1 – Mark Bell Jan 26 '15 at 19:20
  • @MarkBell - you're missing the point. If the font is not mono-width, you'll be able to fit different amounts of characters depending on *which* characters you're using. In your jsbin example, in the second box, that has size="10", I'm able to fit 16 "i"s, but only 7 "w"s. – jbyrd Aug 05 '15 at 02:30
  • 1
    @jbyrd Yes, that is the case—but the answer is correct according to the HTML specification. I've edited the answer now to clarify things a bit. – Mark Bell Aug 05 '15 at 10:19
  • Assuming it's _designed specifically_ for monospace fonts, it begs the question: if the `size` attribute is used with a monospace font, is its precision guaranteed for all font sizes? If not, it's pretty useless don't you think? – bryc Sep 16 '19 at 08:08
  • @bryc Honestly? Yes (also see https://stackoverflow.com/a/6699756/43140). But ten years after I originally wrote this answer, (graphical) browsers which don't support CSS are largely extinct, so I don't really care any more... ;) – Mark Bell Sep 23 '19 at 10:56
54

I suggest, probably best way is to set style's width in em unit :) So for input size of 20 characters just set style='width:20em' :)

Ayush
  • 41,754
  • 51
  • 164
  • 239
Thinker
  • 14,234
  • 9
  • 40
  • 55
  • 6
    Interesting point, however in my tests width:20em makes the input much larger than 20 characters. – Christophe Sep 27 '13 at 18:45
  • 37
    "em" is a measure of the height of the 'M' character, that's why the box gets too large. – humbads Sep 30 '13 at 16:34
  • 11
    In CSS, em is relative to the font-size of its direct or nearest parent. An example: if the inherited font-size of an element is 16px, and you set the font-size to be 2em, the resulting size will be 32px (16px*2em). The "em" unit is not character quantity. More: http://www.w3.org/TR/css3-values/#font-relative-lengths and http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/ and https://j.eremy.net/confused-about-rem-and-em/ – delroh Sep 25 '14 at 16:58
  • 1
    @humbads don't you mean a measure of the *width* of the 'M' character? – Jess Dec 23 '15 at 13:48
  • 5
    @Jess, good question. In [typography](https://en.wikipedia.org/wiki/Em_%28typography%29), 'em' used to mean the width of the 'M' character. For a long time, I believed the same thing. However, in CSS and digital typography, the 'em' equals the height of the font in points. This is to accommodate character sets that do not have the 'M' character, or where the 'M' is not the full height or width of the font. – humbads Dec 23 '15 at 16:42
  • 2
    Maybe you meant `ex`s – Solomon Ucko Mar 10 '16 at 18:08
  • 1
    Re: “...to accommodate character sets that do not have the 'M' character, or...” — this isn’t the case. “Em” had its present meaning (well, some of them — “meanings” is more accurate) ages before digital type and was never defined by “M.” The slug of the letter M was frequently square, or close to it, so it happily lent its name to the concept of a width of the current height. Sometimes it also worked as a reference point for it. But squares in the past, like squares today, don’t become wider or narrower than they are tall even when a typeface has an unusual M. – Semicolon Feb 19 '20 at 13:11
  • 6
    Actually, I think the `ch` unit is best fit for this application. –  Jun 17 '20 at 21:55
24

size is inconsistent across different browsers and their possible font settings.

The width style set in px will at least be consistent, modulo box-sizing issues. You might also want to set the style in ‘em’ if you want to size it relative to the font (though again, this will be inconsistent unless you set the input's font family and size explicitly), or ‘%’ if you are making a liquid-layout form. Either way, a stylesheet is probably preferable to the inline style attribute.

You still need size for <select multiple> to get the height to line up with the options properly. But I'd not use it on an <input>.

Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834
13

I want to say this goes against the "conventional wisdom", but I generally prefer to use size. The reason for this is precisely the reason that many people say not to: the width of the field will vary from browser to browser, depending on font size. Specifically, it will always be large enough to display the specified number of characters, regardless of browser settings.

For example, if I have a date field, I typically want the field wide enough to display either 8 or 10 characters (two digit month and day and either two or four digit year, with separators). Setting the size attribute essentially guarantees me that the entire date will be visible, with minimal wasted space. Similarly for most numbers - I know the range of values expected, so I'll set the size attribute to the proper number of digits, plus decimal point if applicable.

As far as I can tell, no CSS attribute does this. Setting a width in em, for example, is based off the height, not the width, and thus is not very precise if you want to display a known number of characters.

Of course, this logic doesn't always apply - a name entry field, for example, could contain any number of characters. In those cases I'll fall back to CSS width properties, typically in px. However, I would say the majority of fields I make have some sort of known content, and by specifying the size attribute I can make sure that most of the content, in most cases, is displayed without clipping.

ibrewster
  • 3,482
  • 5
  • 42
  • 54
  • You can also use the `ex` unit for this, although using size still simplifies most cases by not having dozens of ids/classes in your css for width. – Forty Oct 28 '17 at 18:06
  • 1
    @Forty Actually, you can't. `ex` is the *height* of a character (specifically, the "X"), not the width - just like `em`. Since there is no fixed relation between the height and width of a character (x or otherwise), there is no reason to believe that using the height of a character to set the width of a field will make the field the proper width to show any given number of characters. It could be wider or narrower, depending on the font. Now the `ch` unit looks promising, but is not supported in IE less than 9, which would have been an issue when I wrote this. – ibrewster Oct 29 '17 at 16:44
  • 1
    Yes, but the height of x is usually never smaller than the width, most of the time actually a little higher or almost the same, so it gets quite close. `ch` could have been better unfortunately, some zeroes are thin and it may not measure the full character space... – Forty Oct 30 '17 at 12:47
  • @Forty True, thus reinforcing my original point that there is no good CSS attribute for setting the width of an input field to a specific number of characters, while the `size` attribute strives to to do exactly that. You may be right that `ex` is a reasonable alternative, but the fact remains that it is a height attribute, not a width attribute. `size` is a width attribute, just not css. – ibrewster Oct 30 '17 at 13:38
9

Both the size attribute in HTML and the width property in CSS will set the width of an <input>. If you want to set the width to something closer to the width of each character use the **ch** unit as in:

input {
    width: 10ch;
}
kohane15
  • 809
  • 12
  • 16
chrisbowman22
  • 176
  • 2
  • 4
5

I just got through fighting with a table that I couldn't make any smaller no matter which element I tried to make smaller the width of the table stayed the same. I searched using firebug but couldn't find the element that was setting the width so high.

Finally I tried changing the size attribute of the input text elements and that fixed it. For some reason the size attribute over-rode the css widths. I was using jQuery to dynamically add rows to a table and it was these rows that contained the inputs. So perhaps when it comes to dynamically adding inputs using the appendTo() function maybe it is better to set the size attribute along with the width.

mark
  • 59
  • 1
  • 1
1

You'll get more consistency if you use width (your second example).

Matt Howell
  • 15,750
  • 7
  • 49
  • 56
1

You can resize using style and width to resize the textbox. Here is the code for it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

</head>
<body>
<div align="center">

    <form method="post">
          <div class="w3-row w3-section">
            <div class="w3-rest" align = "center">
                <input name="lastName" type="text" id="myInput" style="width: 50%">
            </div>
        </div>
    </form>
</div>
</body>
</html>

Use align to center the textbox.

shah
  • 81
  • 1
  • 6
0

HTML controls the semantic meaning of the elements. CSS controls the layout/style of the page. Use CSS when you are controlling your layout.

In short, never use size=""

Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96
  • The size can be inherent in the meaning of the element; for example, a middle initial has a single character. A first name, OTOH, has no inherent size limit — unless you have one in your database. – derobert Sep 26 '09 at 06:53
  • 4
    @derobert: I could be mistaken but normally you express that using the maxlength-attribute for input[type=text|password] and not with the size-attribute. – Horst Gutmann Sep 26 '09 at 07:01
  • 2
    @Horst: Well, I'd express the middle initial with both (as that limit makes sense to the user), and the database limit one only with maxlength. – derobert Sep 26 '09 at 07:23
0

One example where it makes sense

I'd say use size property along with a max-width style; this gives you a close-to-optimal width when there's enough space but limits the input length when it's needed.

<input type="text" size="48" style="max-width:100%;">

See this Codepen.

dkellner
  • 8,726
  • 2
  • 49
  • 47