文本溢出省略号:避免单词中断

Zeu*_*eux 11 css css3

在我的网页中,我有一个固定宽度的div并使用以下css:

width: 200px; 
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
Run Code Online (Sandbox Code Playgroud)

省略号正在起作用,问题是它会删除最后一个单词,我希望它将省略号(...)放在一个完整单词的最后.

例如,如果我有文本:"stackoverflow是最好的",并且如果它需要在接近结束时切割,我希望它显示"stackoverflow是......"而不是"stackoverflow是... "

Juk*_*ela 5

我担心这是不可能的.有一次text-overflow: ellipsis-word,这会做到这一点,但它没有在浏览器中实现,它已从CSS3草稿中删除.


Hun*_*rin 5

当然有可能。(如果您愿意稍微更改标记。)

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>
Run Code Online (Sandbox Code Playgroud)