Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do text-overflow: ellipsis on two lines?

Tags:

css

I have a container where the text may expand to two lines and it's 40px in height, with an 18px font size. When I do:

text-overflow: ellipsis;
white-space: nowrap;

Then the dotted line shows correctly but it gets cut off on one line. When I do just the:

text-overflow: ellipsis;

Then it correctly shows the 2 lines but there's no "..." at the end. How do I achieve this so it correctly uses both lines AND finishes with "..." on the second line?

like image 520
user1227914 Avatar asked Jul 29 '15 10:07

user1227914


2 Answers

Add a span to the container, which will hold the text:

<div class="container">
  <span>text...</span>
</span>

Add this CSS:

.container {
   overflow: hidden;
   position: relative;
   background: white;   //or other color
}

.container:after {
  content: '...';       //the ellipsis
  position: absolute;   //positioned in bottom-right
  bottom: 0;            //...
  right: 0;             //...
  padding: 0 0.3em;     //give some separation from text
  background: inherit;  //same color as container
}

.container span:after {
  content: '\0000a0';   //a space
  position: absolute;   //to cover up ellipsis if needed
  width: 1000px;        //...
  z-index: 1;           //...
  background: white;    //must match container's color.  can't use inherit here.
}

Fiddle

Resize the container, and you'll see that the ellipsis displays only as necessary.

Should work in all modern browsers.

like image 81
Rick Hitchcock Avatar answered Oct 21 '22 21:10

Rick Hitchcock


You can do it using -webkit-line-clamp. But a hack is needed. You need to set the height of the div such that it can accommodate only two lines.

See this codepen https://codepen.io/VamsiKaja/pen/xYZVzY

HTML file :

<p class="">Pellentesque habitant morbi tristique senectus et netus et </p>

CSS file :

p {
    width:250px;  
    font-size:20px;
    margin:1em;
    height:50px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;

}

like image 29
VamsiKaja Avatar answered Oct 21 '22 21:10

VamsiKaja