Search code examples
htmlcssellipsis

How to make div ellipsis with multiple paragraphs inside it?


<div>
 <p>This is a sample text.</p>
 <p>This is a 2nd sample text. existing inside a paragraph. I want to make this ellipsis to avoid overflow text.</p>
 <p>This is a last paragraph which is not going to display as 3 lines are already displayed</p>
</div>

required output -

This is a sample text.
This is a 2nd sample text. existing 
inside a paragraph. I want to make...

I want to make text inside div ellipsis with 3 lines by considering all paragraphs as a single text.
How can I achieve this??

I have tried following one -

div{
 width: 200px;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: initial;
 display: -webkit-box;
 -webkit-line-clamp: 3;
 -webkit-box-orient: vertical;
}
<div>
 <p>This is a sample text.</p>
 <p>This is a 2nd sample text. existing inside a paragraph. I want to make this ellipsis to avoid overflow text.</p>
 <p>This is a last paragraph which is not going to display as 3 lines are already displayed</p>
</div>

But it not working properly as expected if there is multiple paragraph inside div.


Solution

  • Consider display:contents; on the p elements combined with a pseudo element trick to keep the separation between the p

    div {
      width: 400px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: initial;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }
    
    div p {
      display: contents;
    }
    
    p:after {
      content: "\A";
      white-space:pre;
    }
    <div>
      <p>This is a sample text.</p>
      <p>This is a 2nd sample text. existing inside a paragraph. I want to make this ellipsis to avoid overflow text.</p>
      <p>This is a last paragraph which is not going to display as 3 lines are already displayed</p>
    </div>