Offline
Online
Viewers

Responsive CSS Truncate and Ellipsis

We’ve all run into situations where we need to truncate text due to length constraints.  Most of the time this simply requires a truncation function which determines the maximum length of text and if the string exceeds that length, truncates it and adds an ellipsis (“…”).  But what about when we are developing responsive web applications that require text to be truncated according to the current device screen or browser size.  Luckily CSS3 supports a text-transform property called “ellipsis”, this however also requires that the bounding box defined with an overflow and a definite width and height.  Or does it…?

I’ve found an interesting way to implement CSS text truncation in a responsive setting that can be used with responsive layouts such as Pure, Bootstrap, etc.

The following code creates a single line responsive truncate and ellipsis behavior.

[codesyntax lang=”css”]

.truncate-ellipsis {
    display: table;
    table-layout: fixed;
    width: 100%;
    white-space: nowrap;
}

.truncate-ellipsis > * {
    display: table-cell;
    overflow: hidden;
    text-overflow: ellipsis;
}

[/codesyntax]

 

[codesyntax lang=”html4strict”]

<div class="truncate-ellipsis">
    <span>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam porta tortor vitae nisl tincidunt varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut vel ullamcorper tortor. Nullam vel turpis a augue tempor posuere vel quis nibh. Nam ultrices felis turpis, at commodo ipsum tristique non. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse in accumsan dui, finibus pharetra est. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae velit eu dui rutrum pellentesque vel imperdiet sem. Morbi ut lacinia lacus, in commodo nibh. Sed cursus ante ut nunc molestie viverra.
    </span>
</div>

[/codesyntax]

 

This works by taking a parent element, in this case a “div” with the class “truncate-ellipsis” and turning it into a display type table with a fixed table layout. Its child element, in this case a “span” is transformed into a table cell with the overflow set to hidden and the text-transform property set to ellipsis.  This of course can be modified to suit specific needs of height and container size and should act as a pretty good starting point for basic implementation.

24 Comments

  1. Any idea how to have scroll-able content resulting in a box like your html preview is?
    overflow:scroll does not seem to work.

    1. Hi Nenad,

      Certainly, just set the overflow property on the containing element to either “auto” for scroll/no scroll depending on content size or to “scroll” to enforce scrollbars always present.

      #myDiv { overflow: auto }

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Affiliates