Add an Ellipse to Truncated Text with CSS: Single-line and Multi-line Options

Being able to truncate lines of text is fairly easy in CSS, you can explicitly set a width and height of a containing element and set overflow: hidden. As such though this doesn't really tell the user that much and not really that good of an idea. If you want to indicate to the reader that the text has been truncated purposely it is nice to add an ellipse or 3 full stops like so ...

So how is this done, how can you generate an Automatic Ellipses? Again this is fairly easy for single-lines.

 

Single-line Truncate

Single lines you need to set the text-overflow property value to ellipsis.

If your elements wrapping div does not have an explicit height you also need to add white-space: nowrap;,which you are best to use in most use cases anyhow. White-space: nowrap makes sure if the width of you div is too narrow for the length of text that the text does not wrap onto the next line. Here is the code needed to make the H1 in a div show with an ellipsis on a mobile device. I have also set the font size smaller too so this only shows on very few pages but makes sure that the design doesn't break.

#headertitle h1 {
    width: 325px;
    font-size: 0.85em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

Well that was easy

Multi-line Truncate

Multi-line is not much more difficult, it is a combination of 3 properties. The solution is a proprietary CSS property that will limit the text of a block container to a given number of lines when used in combination with display: -webkit-box and -webkit-box-orient: vertical;

Even though it is proprietary is has 96% support in browsers according to Can I use.

 

.views-field-title a {
    color: #125f04;
    text-decoration: none;
    font-size: 0.85em;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    /* not needed even though some documentation says it is
    text-overflow: ellipsis; */
}

1 font-size is set to 0.85em in this example as the links are wrapped in an h2. This will be reworked in the coming weeks as the theme is designed around the content. Please see the homepage of this site on mobile or narrow widths.

 

Support is good for both and as far as I can see useful if you have content that sometimes can be longer than the average. I the case on this site, it would be better practice to make the text smaller for the article titles and this is something I will do when I make some theme modifications in the following weeks.

The first example is the page title in the header, it works okay and it only truncates for small device sizes to the width. Not wanting the header band to take up to much screen I think it works well since it is only a handful of pages.

One final thought on truncating text is you should only do it for edge cases as if every element needs to be truncated then you should think about redesigning the UI.

Tags