blog-banner

Multi-Line Ellipsis Using Simple CSS

  • CSS
  • Design
  • Responsive Design

Multi-Line Ellipsis In CSS

 

The easiest and more bulletproof way to handle multi-line truncation of strings, so I found that we can truncate strings using two carefully placed CSS pseudo-elements.

Here’s the full CSS. We’ll walk through the code below.

    /* styles for '...' */ 
    .block-with-text {
    /* Over flow hidden hides the text if it is more than N lines  */
    overflow: hidden;
    /* To set '...' in absolute position */
    position: relative; 
    /* Use this value to count block height */
    line-height: 1.2em;
    /* Max-height = line-height (1.2) * lines max number (2) */
    max-height: 2.4em; 
    /* If the last visible word doesn't adjoin right side then this will fix the problem */
    text-align: justify !important;  
    /* place for '...' */
    padding-right: 40px;
    padding-left: 1em;
    }

    /* create the ... */
    .block-with-text:before {
    /* points in the end */
    content: '...';
    /* absolute position */
    position: absolute;
    /* set position to right bottom corner of block */
    right: 20px;
    bottom: 0;
    }

    /* hide ... if we have text, which is less than or equal to max lines */
    .block-with-text:after {
    /* points in the end */
    content: '';
    /* absolute position */
    position: absolute;
    /* set position to right bottom corner of text */
    right: 20px;
    /* set width and height */
    width: 1em;
    height: 1em;
    margin-top: 0.2em;
    /* bg color = bg color under block */
    background: white;
    }

Benefits

  • 1. Pure CSS
  • 2. Responsive
  • 3. No need to recalculate on resize or font’s load event
  • 4. Cross-browser

1. The text is more than 3 lines

image

2. The text is less than 3 lines

image

3. The text is exactly 3 lines

image