Css overflow text displayed in few lines without word break

4k views Asked by At

I have some long text that is displayed within a div this div has a fixed width and height. I want the text to be displayed on a few lines (as the div height) and that the sentence words will not break (word prefix in one line and the continue in the next line) furthermore I want to add ellipsis at the end of the last sentence.

CSS:

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

but this displays the text in one line even though the div contains a few lines.

Second option:

word-wrap: break-word;

this unlike the first break the word and the sentence is displayed in a few lines - this is no good since the words are breaking in the middle and at the end of the sentence there is no ellipsis (...)

How can i achieve the following:

1) Few sentences as the div height

2) No word break

3) At the end ellipsis is displayed ( last line contains ellipsis)

attached jsfiddle: https://jsfiddle.net/vghup5jf/1/ as you can see only one line is displayed

2

There are 2 answers

1
Prime On

ellipsis wont work for multiple line and its not possible with pure CSS. Below is the trick which works on chrome and Safari (-webkit rendering engines).

.ellipsis {
    display: block;
    display: -webkit-box;
    max-width: 400px;
    max-height: 100px;
    font-size: 20px;
    line-height: 1.4;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
<div class="ellipsis">
     <span>
       I have a long text that display in div this div has a fixed width and height, I want the text will be displayed in a few lines (as the div height) and that the sentence words will not break(word prefix in one line and the continue in the next line) furthermore I want to add ellipsis at the end of the last sentence.
      </span>
</div>

for cross compatibility you should use SASS or javascript.

Using JS

https://css-tricks.com/line-clampin/

Using CSS-SASS

http://codepen.io/martinwolf/pen/qlFdp

0
Ortal Blumenfeld Lagziel On

Thanks a lot BaTmaN this is the final result :

Added the following css will solve it:

display: -webkit-box !important; -webkit-line-clamp: 2 !important;
   -webkit-box-orient: vertical !important;

and remove: white-space: nowrap;

http://jsfiddle.net/f5n1wrxs/