如何在 `word-break: break-all` 模式下使用自动 CSS 单词断字?

40
我正在使用word-break: break-all;,想知道如何让浏览器自动插入连字符hyphens,就像MDN example中演示的那样。

div {
  width: 80px;
  height: 80px;
  display: block;
  overflow: hidden;
  border: 1px solid red;
  word-break: break-all;
  hyphens: auto;
  -ms-hyphens: auto;
  -moz-hyphens: auto;
}
<div>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>

使文本看起来像这样:

aaaaaaaa-
aaaaaaaa-
aaaaaaaa-
aaaaaaaa

我创建了一个 JSFiddle
这需要在IE9/IE10中工作,但如果在Firefox和Chrome中也能工作那就更好了。
4个回答

30
“word-break”属性和断字是两个完全不同的东西。第一个最初主要用于东亚语言,对于像英语这样的语言会做出一些不好的事情:它会在某些点上任意切断单词而不指示单词已被分割。
因此,您应该决定是否有表达式可以在浏览器中的任何位置插入换行符,或者您是否需要断字。
对于断字,CSS代码本身是可以的,尽管许多人建议将标准属性设置“hyphens: auto”放在前缀属性之后。但它要求在HTML标记中声明文本的语言,例如使用“<div lang=en>”。此外,浏览器支持仍然有限:IE 9不支持这种连字符,IE 10的支持范围涵盖了相对较少的语言(当然包括英语)。
对于IE 9上的自动断字,您需要使用服务器端编程断字或者更简单的客户端断字工具,例如Hyphenator.js

14

你能解释一下那个 jsfiddle 怎么工作的吗?我应该在哪里插入 ­ ? - user1380540
@user1380540 你可以在任何你认为需要手动分隔单词的地方插入 &shy; 来实现软连字符的效果。 - Volker E.
1
感谢您的支持。 - Shashank Bhatt

13
"

-ms-hyphens属性仅在IE10+中可用,无法在IE9或更早版本中使用。

请参见您提供的参考链接底部的浏览器兼容性图表。

目前在Chrome中还不起作用:WebKit连字化

"

9
截至2015年,世界还没有准备好使用CSS连字符:http://caniuse.com/#feat=css-hyphens - Hannes Schneidermayer

1

我没有找到任何CSS解决方案,所以用JS来修复它。

const addWordBreaks = (str, maxLength = 10) => {
    const words = str.split(" ");
    const newWords = [];
    words.forEach(function(word) {
      if (word.length > maxLength) {
        const firstWord = word.substr(0,maxLength);
        const endWord = word.substr(maxLength, word.length-1);
        newWords.push(firstWord +"- \n");
        newWords.push(endWord)
      } else {
        newWords.push(word)
      }
    });
     return newWords.join(" ");
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接