I'm trying to display a series of titles varying from 60 characters to 160 or so and the capitalization varies, some of it all caps, some half caps. When it's mostly lowercase the whole 160 characters of text fits in the width I want, but when it starts getting more caps (they must be wider), it starts over flowing.
Is there a way to use an attractive fixed witdh font (upper and lowercase widths the same too), or dynamically shrink the text to fit, or otherwise recognize how much space the text is going to take on the server side, and cut off the end dynamically? Or do you folks have a better solution?
Control the Overflow
The real trick is just setting a limit on size of the text box, and making sure that there aren't overflow problems. You can use overflow: hidden to take care of this, and display: block the element in order to give it the exact dimensions you need.
Monospace is Optional
Yes, you can use a monospace font.. there are only a few to choose from if you want a cross-browser solution. You can use a variable-width font, too.. the monospace will just help you get consistency with the capitalization problem you described. Using a monospace font will help you to choose a good width that will work for different text lengths. In my example below, I've arbitrarily chosen a width of 250 pixels, and typed strings until they were well past the limit, just for the purposes of illustration.
Line-heights and Margins
You want the line height of the text to match the height of the box.. in this case, I've used 20 pixels. If you need to create line height, you can add a bottom margin.
Side note: I've used an h3 here, because the text is repeated many times across the page. In general it's a better choice to use a lower level of header for more common text (just a semantic choice). Using an h1 will work the same way..
<html>
<head>
<title>h1 stackoverflow question</title>
<style type="text/css">
* { margin:0; padding:0 }
h3 {
display: block;
width: 250px;
height: 20px;
margin-bottom: 5px;
overflow: hidden;
font-family: Courier, Lucidatypewriter, monospace;
font: normal 20px/20px Courier;
border: 1px solid red;
}
</style>
</head>
<body>
<h3>Hello, World</h3>
<h3>Lorem Ipsum dolor sit Amet</h3>
<h3>Adipiscing Lorem dolor sit lorem ipsum</h3>
<h3>"C" is for Cookie, that's good enough for lorem ipsum</h3>
<h3>Oh, it's a lorem ipsum dolor sit amet. Adipiscing elit.</h3>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With