[html] Applying an ellipsis to multiline text

Is there a solution to add ellipsis on last line inside a div with a fluid height (20%)?

I found the -webkit-line-clamp function in CSS, but in my case the line number will be depending on window size.

_x000D_
_x000D_
p {_x000D_
    width:100%;_x000D_
    height:20%;_x000D_
    background:red;_x000D_
    position:absolute;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
_x000D_
_x000D_
_x000D_

I have this JSFiddle to illustrate the issue. https://jsfiddle.net/96knodm6/

This question is related to html css ellipsis

The answer is


Pros:
+ Cross browser (IE11, Edge, Chrome, Firefox, Safari, etc.)
+ Most natural looking

Cons:
- Adds lots of extra elements to the DOM

I wasn't satisfied with any of the workarounds I had seen. Most of them use line-clamp which is currently only supported in webkit. So I played around with it until I came up with a solution. This pure javascript solution should be compatible with IE10 and greater and all modern browsers. This is untested outside of the stackoverflow example space below.

I think this is a good solution. The one big caveat is that it creates a span for each word inside the container, which will impact layout performance, so your mileage may vary.

_x000D_
_x000D_
//This is designed to be run on page load, but if you wanted you could put all of this in a function and addEventListener and call it whenever the container is resized._x000D_
var $container = document.querySelector('.ellipses-container');_x000D_
_x000D_
//optional - show the full text on hover with a simple title attribute_x000D_
$container.title = $container.textContent.trim();_x000D_
_x000D_
$container.textContent.trim().split(' ').some(function (word) {_x000D_
  //create a span for each word and append it to the container_x000D_
  var newWordSpan = document.createElement('span');_x000D_
  newWordSpan.textContent = word;_x000D_
  $container.appendChild(newWordSpan);_x000D_
  _x000D_
  if (newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {_x000D_
    //it gets into this block for the first element that has part of itself below the bottom of the container_x000D_
    //get the last visible element_x000D_
    var containerChildNodes = $container.childNodes;_x000D_
    var lastVisibleElement = containerChildNodes[containerChildNodes.length - 2];_x000D_
    _x000D_
    //replace this final span with the ellipsis character_x000D_
    newWordSpan.textContent = '\u2026';_x000D_
    _x000D_
    //if the last visible word ended very near the end of the line the ellipsis will have wrapped to the next line, so we need to remove letters from the last visible word_x000D_
    while (lastVisibleElement.textContent != "" && newWordSpan.getBoundingClientRect().bottom > $container.getBoundingClientRect().bottom) {_x000D_
      lastVisibleElement.style.marginRight = 0;_x000D_
      lastVisibleElement.textContent = lastVisibleElement.textContent.slice(0, -1);_x000D_
    }_x000D_
    _x000D_
    //using .some() so that we can short circuit at this point and no more spans will be added_x000D_
    return true;_x000D_
  }_x000D_
});
_x000D_
.multi-line-container {_x000D_
  border: 1px solid lightgrey;_x000D_
  padding: 4px;_x000D_
  height: 150px;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
.ellipses-container {_x000D_
  display: inline-flex;_x000D_
  flex-wrap: wrap;_x000D_
  justify-content: flex-start;_x000D_
  align-content: flex-start; /* optionally use align-content:stretch, the default, if you don't like the extra space at the bottom of the box if there's a half-line gap */_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.ellipses-container > span {_x000D_
  flex: 0 0 auto;_x000D_
  margin-right: .25em;_x000D_
}_x000D_
_x000D_
.text-body {_x000D_
  display: none;_x000D_
}
_x000D_
<div class="multi-line-container ellipses-container">_x000D_
  <div class="text-body ellipses-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque luctus ut massa eget porttitor. Nulla a eros sit amet ex scelerisque iaculis nec vitae turpis. Sed pharetra tincidunt ante, in mollis turpis consectetur at. Praesent venenatis pulvinar lectus, at tincidunt nunc finibus non. Duis tortor lectus, elementum faucibus bibendum vitae, egestas bibendum ex. Maecenas vitae augue vitae dui condimentum imperdiet sit amet mattis quam. Duis eleifend scelerisque magna sed imperdiet. Mauris tempus rutrum metus, a ullamcorper erat fringilla a. Suspendisse potenti. Praesent et mi enim. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


p{
line-height: 20px;
width: 157px;
white-space: nowrap; 
overflow: hidden;
text-overflow: ellipsis;
}

or we can restrict the lines by using and height and overflow.


<!DOCTYPE html>
<html>
<head>
    <style>
        /* styles for '...' */
        .block-with-text {
            width: 50px;
            height: 50px;
            /* hide text if it more than N lines  */
            overflow: hidden;
            /* for 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 (3) */
            max-height: 3.6em;
            /* fix problem when last visible word doesn't adjoin right side  */
            text-align: justify;
            /* place for '...' */
            margin-right: -1em;
            padding-right: 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: 0;
                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: 0;
                /* set width and height */
                width: 1em;
                height: 1em;
                margin-top: 0.2em;
                /* bg color = bg color under block */
                background: white;
            }
    </style>
</head>
<body>
    a
    <div class="block-with-text">g fdsfkjsndasdasd asd asd asdf asdf asdf asdfas dfa sdf asdflk jgnsdlfkgj nsldkfgjnsldkfjgn sldkfjgnls dkfjgns ldkfjgn sldkfjngl sdkfjngls dkfjnglsdfkjng lsdkfjgn sdfgsd</div>
    <p>This is a paragraph.</p>

</body>
</html>

My solution that works for me for multiline ellipsis:

.crd-para {
    color: $txt-clr-main;
    line-height: 2rem;
    font-weight: 600;
    margin-bottom: 1rem !important;
    overflow: hidden;

    span::after {
        content: "...";
        padding-left: 0.125rem;
    }
}

You can achieve this by a few lines of CSS and JS.

CSS:

        div.clip-context {
          max-height: 95px;
          word-break: break-all;
          white-space: normal;
          word-wrap: break-word; //Breaking unicode line for MS-Edge works with this property;
        }

JS:

        $(document).ready(function(){
             for(let c of $("div.clip-context")){
                    //If each of element content exceeds 95px its css height, extract some first 
                    //lines by specifying first length of its text content. 
                   if($(c).innerHeight() >= 95){
                        //Define text length for extracting, here 170.
                        $(c).text($(c).text().substr(0, 170)); 
                        $(c).append(" ...");
                   }
             }

        });

HTML:

        <div class="clip-context">
            (Here some text)
        </div>

If you want to apply ellipsis (...) to a single line of text, CSS makes that somewhat easy with the text-overflow property. It's still a bit tricky (due to all the requirements – see below), but text-overflow makes it possible and reliable.

If, however, you want to use ellipsis on multiline text – as would be the case here – then don't expect to have any fun. CSS has no standard method for doing this, and the workarounds are hit and miss.

Ellipsis for Single Line Text

With text-overflow, ellipsis can be applied to a single line of text. The following CSS requirements must be met:

  • must have a width, max-width or flex-basis
  • must have white-space: nowrap
  • must have overflow with value other than visible
  • must be display: block or inline-block (or the functional equivalent, such as a flex item).

So this will work:

_x000D_
_x000D_
p {_x000D_
  width: 200px;_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  display: inline-block;_x000D_
  text-overflow: ellipsis;_x000D_
  border: 1px solid #ddd;_x000D_
  margin: 0;_x000D_
}
_x000D_
<p>_x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>. _x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>. _x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>. _x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>._x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>._x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>._x000D_
</p>
_x000D_
_x000D_
_x000D_

jsFiddle version

BUT, try removing the width, or letting the overflow default to visible, or removing white-space: nowrap, or using something other than a block container element, AND, ellipsis fails miserably.

One big takeaway here: text-overflow: ellipsis has no effect on multiline text. (The white-space: nowrap requirement alone eliminates that possibility.)

_x000D_
_x000D_
p {_x000D_
    width: 200px;_x000D_
    /* white-space: nowrap; */_x000D_
    height: 90px; /* new */_x000D_
    overflow: hidden;_x000D_
    display: inline-block;_x000D_
    text-overflow: ellipsis;_x000D_
    border: 1px solid #ddd;_x000D_
    margin: 0;_x000D_
}
_x000D_
<p>_x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>. _x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>. _x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>. _x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>._x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>._x000D_
  This is a test of CSS <i>text-overflow: ellipsis</i>._x000D_
</p>
_x000D_
_x000D_
_x000D_

jsFiddle version


Ellipsis for Multiline Text

Because CSS has no property for ellipsis on multiline text, various workarounds have been created. Several of these methods can be found here:

The Mobify link above was removed and now references an archive.org copy, but appears to be implemented in this codepen.


Please check this below code for pure css trick with proper alignment which supports for all browsers

_x000D_
_x000D_
.block-with-text {
    overflow: hidden;
    position: relative;
    line-height: 1.2em;
    max-height: 103px;
    text-align: justify;
    padding: 15px;
}

.block-with-text:after {
    content: '...';
    position: absolute;
    right: 15px;
    bottom: -4px;
    background: linear-gradient(to right, #fffff2, #fff, #fff, #fff);
}
_x000D_
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon; use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>
_x000D_
_x000D_
_x000D_


To bad CSS doesn't support cross-browser multiline clamping, only webkit seems to be pushing it.

You could try and use a simple Javascript ellipsis library like Ellipsity on github the source code is very clean and small so if you do need to make any additional changes it should be quite easy.

https://github.com/Xela101/Ellipsity


If you are using javascript, maybe you can do something like below. However, this does not account the height of the container...

_x000D_
_x000D_
// whatever string_x000D_
const myString = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pellentesque sem ut consequat pulvinar. Curabitur vehicula quam sit amet risus aliquet, sed rhoncus tortor fermentum. Etiam ac fermentum nisi. Ut in lobortis eros. Etiam urna felis, interdum sit amet fringilla eu, bibendum et nunc.';_x000D_
_x000D_
// you can set max string length_x000D_
const maxStrLength = 100;_x000D_
const truncatedString = myString.length > maxStrLength ? `${myString.substring(0, maxStrLength)}...` : myString;_x000D_
_x000D_
console.log(truncatedString);
_x000D_
_x000D_
_x000D_


I have just been playing around a little bit with this concept. Basically, if you are ok with potentially having a pixel or so cut off from your last character, here is a pure css and html solution:

The way this works is by absolutely positioning a div below the viewable region of a viewport. We want the div to offset up into the visible region as our content grows. If the content grows too much, our div will offset too high, so upper bound the height our content can grow.

HTML:

<div class="text-container">
  <span class="text-content">
    PUT YOUR TEXT HERE
    <div class="ellipsis">...</div> // You could even make this a pseudo-element
  </span>
</div>

CSS:

.text-container {
    position: relative;
    display: block;
    color: #838485;
    width: 24em;
    height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
    overflow: hidden;
    white-space: normal;
}

.text-content {
  word-break: break-all;
  position: relative;
  display: block;
  max-height: 3em;       // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport 
}

.ellipsis {
  position: absolute;
  right: 0;
  top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
  text-align: left;
  background: white;
}

I have tested this in Chrome, FF, Safari, and IE 11.

You can check it out here: http://codepen.io/puopg/pen/vKWJwK

You might even be able to alleviate the abrupt cut off of the character with some CSS magic.

EDIT: I guess one thing that this imposes is word-break: break-all since otherwise the content would not extend to the very end of the viewport. :(


Please check this css for ellipsis to multi-line text

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 50px;_x000D_
}_x000D_
_x000D_
/* mixin for multiline */_x000D_
.block-with-text {_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  line-height: 1.2em;_x000D_
  max-height: 6em;_x000D_
  text-align: justify;_x000D_
  margin-right: -1em;_x000D_
  padding-right: 1em;_x000D_
}_x000D_
.block-with-text:before {_x000D_
  content: '...';_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}_x000D_
.block-with-text:after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  width: 1em;_x000D_
  height: 1em;_x000D_
  margin-top: 0.2em;_x000D_
  background: white;_x000D_
}
_x000D_
<p class="block-with-text">The Hitch Hiker's Guide to the Galaxy has a few things to say on the subject of towels. A towel, it says, is about the most massivelyuseful thing an interstellar hitch hiker can have. Partly it has great practical value - you can wrap it around you for warmth as you bound across the cold moons of  Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon;  use it to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to-hand-combat; wrap it round your head to ward off noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough. More importantly, a towel has immense psychological value. For some reason, if a strag (strag: non-hitch hiker) discovers that a hitch hiker has his towel with him, he will automatically assume that he is also in possession of a toothbrush, face flannel, soap, tin of biscuits, flask, compass, map, ball of string, gnat spray, wet weather gear, space suit etc., etc. Furthermore, the strag will then happily lend the hitch hiker any of these or a dozen other items that the hitch hiker might accidentally have "lost". What the strag will think is that any man who can hitch the length and breadth of the galaxy, rough it, slum it, struggle against terrible odds, win through, and still knows where his towel is is clearly a man to be reckoned with.</p>
_x000D_
_x000D_
_x000D_


After looking all over the internet and trying a lot of these options, the only way to make sure that it is covered correctly with support for i.e is through javascript, i created a loop function to go over post items that require multi line truncation.

*note i used Jquery, and requires your post__items class to have a fixed max-height.

// loop over post items
$('.post__items').each(function(){
    var textArray = $(this).text().split(' ');
    while($(this).prop('scrollHeight') > $(this).prop('offsetHeight')) {
        textArray.pop();
        $(this).text(textArray.join(' ') + '...');
     }
});

_x000D_
_x000D_
p {_x000D_
    width:100%;_x000D_
    overflow: hidden;_x000D_
    display: -webkit-box;_x000D_
    -webkit-line-clamp: 2;_x000D_
    -webkit-box-orient: vertical;_x000D_
    background:#fff;_x000D_
    position:absolute;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
_x000D_
_x000D_
_x000D_


May be this can help you guys. Multi Line Ellipses with tooltip hover. https://codepen.io/Anugraha123/pen/WOBdOb

<div>
     <p class="cards-values">Lorem ipsum dolor sit amet,   consectetur adipiscing elit. Nunc aliquet lorem commodo, semper mauris nec, suscipit nisi. Nullam laoreet massa sit amet leo malesuada imperdiet eu a augue. Sed ac diam quis ante congue volutpat non vitae sem. Vivamus a felis id dui aliquam tempus
      </p>
      <span class="tooltip"></span>
</div>

I came up with my own solution for this:

/*this JS code puts the ellipsis (...) at the end of multiline ellipsis elements
 *
 * to use the multiline ellipsis on an element give it the following CSS properties
 * line-height:xxx
 * height:xxx (must line-height * number of wanted lines)
 * overflow:hidden
 *
 * and have the class js_ellipsis
 * */

//do all ellipsis when jQuery loads
jQuery(document).ready(function($) {put_ellipsisses();});

//redo ellipsis when window resizes
var re_ellipsis_timeout;
jQuery( window ).resize(function() {
    //timeout mechanism prevents from chain calling the function on resize
    clearTimeout(re_ellipsis_timeout);
    re_ellipsis_timeout = setTimeout(function(){ console.log("re_ellipsis_timeout finishes"); put_ellipsisses(); }, 500);
});

//the main function
function put_ellipsisses(){
    jQuery(".js_ellipsis").each(function(){

        //remember initial text to be able to regrow when space increases
        var object_data=jQuery(this).data();
        if(typeof object_data.oldtext != "undefined"){
            jQuery(this).text(object_data.oldtext);
        }else{
            object_data.oldtext = jQuery(this).text();
            jQuery(this).data(object_data);
        }

        //truncate and ellipsis
        var clientHeight = this.clientHeight;
        var maxturns=100; var countturns=0;
        while (this.scrollHeight > clientHeight && countturns < maxturns) {
            countturns++;
            jQuery(this).text(function (index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
        }
    });
}

Unfortunately no with current state of affairs in CSS.

Ellipsis rendering has prerequisite white-space:nowrap that effectively means: ellipsis are drawn on single line text containers only.


This man have the best solution. Only css:

.multiline-ellipsis {
    display: block;
    display: -webkit-box;
    max-width: 400px;
    height: 109.2px;
    margin: 0 auto;
    font-size: 26px;
    line-height: 1.4;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

If you also have multiple elements and you want a link with read more button after ellipsis, take a look on https://stackoverflow.com/a/51418807/10104342

If you want something like this:

Every month first 10 TB are are not charged. All other traffic... Read more


Just increase the -webkit-line-clamp: 4; to increase the number of lines

_x000D_
_x000D_
p {
    display: -webkit-box;
    max-width: 200px;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
_x000D_
<p>Lorem ipsum dolor sit amet, novum menandri adversarium ad vim, ad his persius nostrud conclusionemque. Ne qui atomorum pericula honestatis. Te usu quaeque detracto, idque nulla pro ne, ponderum invidunt eu duo. Vel velit tincidunt in, nulla bonorum id eam, vix ad fastidii consequat definitionem.</p>
_x000D_
_x000D_
_x000D_


Line clamp is a proprietary and undocumented CSS (webkit) : https://caniuse.com/#feat=css-line-clamp, so it currently work on only few browsers.

Removed duplicated 'display' property + removed unnecessary 'text-overflow: ellipsis'.


I took a look at how YouTube solves it on their homepage and simplified it:

.multine-ellipsis {
  -webkit-box-orient: vertical;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}

This will allow 2 lines of code and then append an ellipsis.

Gist: https://gist.github.com/eddybrando/386d3350c0b794ea87a2082bf4ab014b


After many tries, I finally ended up with a mixed js / css to handle multiline and single line overflows.

CSS3 code:

.forcewrap { // single line ellipsis
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  overflow: hidden;
  -moz-binding: url( 'bindings.xml#ellipsis' );
  white-space: nowrap;
  display: block;
  max-width: 95%; // spare space for ellipsis
}

.forcewrap.multiline {
  line-height: 1.2em;  // my line spacing 
  max-height: 3.6em;   // 3 lines
  white-space: normal;
}

.manual-ellipsis:after {
  content: "\02026";      // '...'
  position: absolute;     // parent container must be position: relative
  right: 10px;            // typical padding around my text
  bottom: 10px;           // same reason as above
  padding-left: 5px;      // spare some space before ellipsis
  background-color: #fff; // hide text behind
}

and I simply check with js code for overflows on divs, like this:

function handleMultilineOverflow(div) {
    // get actual element that is overflowing, an anchor 'a' in my case
    var element = $(div).find('a'); 
    // don't know why but must get scrollHeight by jquery for anchors
    if ($(element).innerHeight() < $(element).prop('scrollHeight')) {
        $(element).addClass('manual-ellipsis');
    }
}

Usage example in html:

<div class="towrap">
  <h4>
    <a class="forcewrap multiline" href="/some/ref">Very long text</a>
  </h4>
</div>

Well you could use the line-clamp function in CSS3.

p {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-height: 25px;
    height: 52px;
    max-height: 52px;
    font-size: 22px;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

Make sure you change the settings like you're own.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to ellipsis

What is the hamburger menu icon called and the three vertical dots icon called? Applying an ellipsis to multiline text How to have Ellipsis effect on Text CSS text-overflow: ellipsis; not working? Android, How to limit width of TextView (and add three dots at the end of text)? Why doesn't CSS ellipsis work in table cell? HTML text-overflow ellipsis detection With CSS, use "..." for overflowed block of multi-lines HTML - how can I show tooltip ONLY when ellipsis is activated Limit text length to n lines using CSS