Wednesday, October 29, 2008

Dynamic Text in a Limited Amount of Space

A common problem I've seen when working with dynamic text is you sometimes don't know how much text the end user is going to enter, and this can be a problem when you have a limited amount of space. Generally, you set the container to overflow:hidden and be done with it. The problem with this is that sometimes your text gets cut off in the middle of the line so only the tops of the letters can be seen. It's especially a pain when you are never 100% sure that your users are going to have the correct font.

One solution is to limit the amount of characters, but this isn't always very consistent with the varying sizes of words - you can end up with more or less space available than desired. I decided I wanted to limit the amount of lines, and was able to achieve this with just CSS:

.box {
width: 50px;
height: 50px;
}

.box span {
display: block;
font-size: 10px;
line-height: 14px;
height: 42px;
overflow: hidden;
}

<div class="box">
<span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.</span>
</div>

The line-height here is important, and then setting the height to 42px limits our text to 3 lines (14 x 3 = 42). A "read more" link can then be added after the span, if desired.

No comments: