Input size vs width

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

10 Answers

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;
}

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.

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.

Related