tags:

views:

459

answers:

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

or

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

Which one is optimal Cross-browser friendly code?

Of course, it depends on requirement but curious to know how people around decide which on what basis. (afraid I expressed my question clearly)

+3  A: 

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.

Also I'd recommend styling the fields in a stylesheet rather than inline.

Edit: sorry, I should have mentioned that the size attribute isn't a precise method of sizing - it refers to the number of characters the field will be able to display at once.

Mark B
@Mark B. Thanks for your answer. I used inline style for asking question here.
rajakvk
No worries - I thought you might have, but I just pointed it out in case.
Mark B
A: 

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
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
@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
@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
+1  A: 

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

bigmattyh
+1  A: 

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' :)

Thinker
A: 

CSS FTW!

em's are safe bets, and so are widths!

Tisch
+1  A: 

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>.

bobince