George Armhold
George Armhold

Reputation: 31074

Intelligently clipping text that exceeds a box boundary

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.

Upvotes: 0

Views: 1472

Answers (2)

Robert Koritnik
Robert Koritnik

Reputation: 105059

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.

Upvotes: 0

casablanca
casablanca

Reputation: 70721

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 */

Upvotes: 5

Related Questions