I've been working on a project where we have a big description field that we want to display to our users. The field is of indeterminate length. If it expands beyond the scope of our allotted space in the UI, we want to automatically truncate that and show an ellipse.
How do we make that work? Some CSS magic.
First, let's create a div with a lot of text:
2 This is something with a lot of text. The Quick Brown Fox Jumped over the Lazy Dogs. The whole purpose here is to extend the text beyond multiple lines with a lot of space so that we can demonstrate truncating it inside a div that has multiple lines and extra dots.
3</div>
Nothing special about that. Let's add some magic CSS to force the text to truncate:
2 display: -webkit-box;
3 -webkit-box-orient: vertical;
4 -webkit-line-clamp: 2;
5 overflow: hidden
6}
We're using a lot of weird properties. What is going on here?
First, we set the display property to webkit-box. This is a special, experimental display version built for web kit. It is, however, supported in most browsers. The webkit-box text prepends the following properties.
Next, we use webkit-box-orient which tells us which way the text flows. The webkit-line-clamp property tells CSS at what point we need to truncate the text. In this case, right after line 2.
Finally, we add overflow: hidden to make sure the text after our second line is truncated. It should look a bit like this:
I experimented a bit with looking for ways to do this without using the webkit-box, but did not see anything as easy or trivial.