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

后端 未结 2 1785
小蘑菇
小蘑菇 2021-01-18 05:10

I want to specify the width of textareas in terms of the maximum numbers of monospace characters they should be able to hold in each line with neither excess le

2条回答
  •  广开言路
    2021-01-18 05:35

    It's debatable whether this qualifies as professional, but you can style the textarea to use a fixed width font

    textarea {
        font-family: Courier;
    }
    

    and then set its width in either em or ex units. The exact width to use, however, will depend on the specific font and it may be subject to slight differences in browser font rendering. Here's an example on codepen.

    With this approach the "fudge factor" won't have as wide as a variance (it's pretty much the same on all browsers), but you're limited to fonts that you're confident will be available on the client. Courier is probably the closest you can get to being safe in most cases.

    Here's the result in Chrome:

    Firefox:

    and Safari:

    As you can see, there are definite differences in how the browsers compute a default font size, but in all cases they correctly set the width of the text area to the specified number of characters.

提交回复
热议问题