0

I need to display some text in a box with an explicit width/height. If the text content exceeds the height of the box, I'd like to be truncated, preferably with an ellipsis.

I tried using overflow: hidden, like so:

<div style="width: 500px; height: 50px; 
     overflow: hidden; 
     border: 1px solid black;">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ut sem orci. Sed laoreet, diam sed porttitor rhoncus, erat ante volutpat metus, dignissim laoreet lacus dolor a nisi. Fusce elit libero, interdum vel cursus tincidunt, vulputate quis lorem. In accumsan pharetra mauris, id vulputate sapien condimentum in. Etiam quis laoreet lectus
</div>

But that often results in a line of text being partially visible, like this:

sliced text image

I thought about counting characters and manually truncating the text, but that won't help when the font is proportional.

George Armhold
  • 30,824
  • 50
  • 153
  • 232
  • You can do this for a single line, but I don't believe there's a way to do it for a multi-line box, like you're looking for. More information here: http://stackoverflow.com/questions/802175/truncating-long-strings-with-css-feasible-yet – RussellUresti Mar 24 '11 at 18:28

2 Answers2

5

Try using line-height to fix the height of each line, then set your container height to be a multiple of the line height. For example:

line-height: 15px;
height: 45px; /* 3 lines */
casablanca
  • 69,683
  • 7
  • 133
  • 150
  • 1
    Just a quick note based on what he said about the font being proportional... You might want to use em instead of px just so that the sizing is all relative to the actual size of the font. – TehOne Mar 24 '11 at 18:33
  • This was my solution too. Noticed it doesn't work when the user changes font size / zooms in the browser. – smcphill Mar 24 '11 at 18:37
0

Dummy invisible div

If you can't set height according to @casablanca's suggestion I suggest you clip text using a dummy invisible div as described in a different answer of mine.

Community
  • 1
  • 1
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404