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:
I thought about counting characters and manually truncating the text, but that won't help when the font is proportional.
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 */
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.
精彩评论