How to fix the width of textarea in number of characters? (cols attribute does NOT work)

The col attribute gives accurate results, but the width is somewhat larger than needed for the characters, since there is room for vertical scroll bar on the right (or left, depending on directionality). You can see this by entering a few more lines in the area.

You can remove the room for scroll bar by removing scrollability, using overflow: hidden.

An alternative to set the width in ch units, but browser support is more limited.

textarea {
    resize:none;
    background-color:lightgray;
    padding:0;
    font-family: monospace;
}
.fix {
    overflow: hidden;
}
.w18 {
    width: 18ch;
}
<textarea cols="18" rows="2">123456789012345678</textarea>
<p>See what happens when vertical scrolling is needed:<br>
<textarea cols="18" rows="2">123456789012345678
123
123</textarea>
<p>Fixed by removing space for scroll bar:<br>
<textarea cols="18" rows="2" class="fix">123456789012345678</textarea>
<p>Fixed by setting width in `ch` units:<br>
<textarea cols="18" rows="2" class="w18">123456789012345678</textarea>

As the demo shows, overflow: hidden also removes the space for a horizontal scroll bar. Browsers generally leave such a space, so that the area seems to have one row more than the value of rows, even though browsers normally do not show a horizontal scroll bar as they used to (they visually break lines instead). Using overflow-y: hidden instead keeps that space

You need to consider what the removal of scroll bars implies in terms of usability. If the intent is to show the user the maximum allowed line length, maybe you can do that by forcing a scroll bar instead of removing it.

<textarea cols="18" rows="2" style="overflow-y: scroll; overflow-x: hidden; resize: none">123456789012345678</textarea>

Tags:

Html

Css