text overflow ellipsis: avoid word break

In my webpage I have a div with fixed width and using the following css:

width: 200px; 
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

The ellipsis is working, the problem is that it cuts the final word, and I wanted it to put the ellipsis (...) in the final of a full word.

For instance, if I have the text: "stackoverflow is the best", and if it need to be cutted near the end, I want it to display "stackoverflow is the ..." instead of "stackoverflow is the be..."


Solution 1:

I’m afraid it’s impossible. There was once text-overflow: ellipsis-word, which would do just this, but it was not implemented in browsers and it was removed from CSS3 drafts.

Solution 2:

Of course it's possible. (If you're willing to change your markup a bit.)

https://jsfiddle.net/warphLcr/

<style>
  .foo {
    /* Make it easy to see where the cutoff point is */
    border: 2px solid #999;

    padding-right: 18px; /* Always have room for an ellipsis */
    width: 120px;
    height: 1.1em; /* Only allow one line of text */
    overflow: hidden; /* Hide all the text below that line */
    background-color: #fff; /* Background color is required */
  }
  .foo > span {
    display: inline-block; /* These have to be inline block to wrap correctly */
    position: relative; /* Give the ellipsis an anchor point so it's positioned after the word */
    background-color: #fff; /* Cover the ellipsis of the previous word with the same background color */
    white-space: pre; /* Make sure the only point where wrapping is allowed is after a whole word */
  }
  .foo > span:after {
    position: absolute; /* Take the ellipsis out of the flow, so the next item will cover it */
    content: "…"; /* Each span has an ellipsis */
  }
  .foo > span:last-child:after {
    content: ""; /* Except for the last one */
  }
</style>

<div class="foo">
  <!-- These *must not* have white space between them, or it will collapse to a space before the next word, and the ellipsis will become visible -->
  <span>stackoverflow</span><span> is</span><span> the</span><span> best</span>
</div>