Limit width of text in characters
Someone asked me how they can set up a box of text and limit the width to a certain number of characters. the PRE tag (in some things I found online) used to (?) to have a width attribute, but it doesn’t seem to work in IE 5+. The only way I could do is like this:
<style type=”text/css”>
.test {
overflow: hidden;
border: 0;
font-family: “Courier New”, Courier, mono;
}
</style>
<textarea cols=”10″ rows=”12″ wrap=”VIRTUAL” class=”test”>Lorem ipsum dolor sit amet no nummy some more text, blah blah blah 01234567890</textarea>
(this would limit the width to 10 characters like this:
Can you think of any other way?
update See comments - there *is* a better way…
June 3rd, 2003 at 4:07 pm
By “text box” are you talking about a form input, or just a <div> with text inside?
You can use the “width:??ex” css property, to set an element’s width to some number of characters. Where ?? is the number of characters. “ex” is the width of the letter “x” in the current font & size.
See this page for more information on css widths:
Example:
< div style=”width:15ex;margin:20px;padding:5px;border:1px solid #000000;” >
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce varius. Nullam quam. Suspendisse potenti. Vivamus et nibh. Duis volutpat dolor in ipsum.
</div>
June 3rd, 2003 at 4:11 pm
Excellent! Thanks Lloyd! Just what I was looking for.
June 4th, 2003 at 6:33 pm
i’ve hopefully finally fixed that irksome problem of the sidebar overlapping the posts if the user’s browser text-size is set…
June 6th, 2003 at 1:16 am
awesome! Thanks for the tip!
June 20th, 2003 at 7:32 pm
While ex theoretically is a fine suggestion, please remember that Mozilla handles ex differently from other browsers, so your results many not be entirely what you expect.
In Mozilla, an ex is relative to the fonts aspect ratio, and varies with which font you use, while in MSIE, Opera and Safari/Konqueror, 1ex = 0.5em. http://www.xs4all.nl/~sbpoley/webmatters/emex.html goes in more detail on this.
My suggestion? If you want a <pre> that’s 15 characters wide, use 7.5em for it’s width.
June 30th, 2004 at 9:05 am
One useful application of this is a way to limit the maximum width of text. Text with more than 50-80 characters per line is hard to read. Now, while not all browsers support this, those that are using browsers that do will have a better experience on a site. It is especially useful on liquid sites, where on large resolutions the text becomes very hard to read.
content {
max-width: 40em;
}