36

我正在使用word-break: break-all;并想知道如何让浏览器自动插入连字符,如MDN 示例中所示。

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

4 回答 4

28

word-break属性和连字符是两个完全不同的东西。第一个,最初主要是为东亚语言设计的,对像英语这样的语言造成了不好的影响:它在某些点上任意截断单词,而没有指出单词已经断了。

所以你应该决定你是否有一个表达式,浏览器可以在任何时候插入换行符,或者你是否想要连字符。

对于连字符,CSS 代码本身是可以的,尽管许多人会建议将标准属性设置放在hyphens: auto最后,在前缀属性之后。但它要求在 HTML 标记中声明文本的语言,例如使用<div lang=en>. 此外,浏览器支持仍然有限:IE 9 不支持这种连字符,而 IE 10 中的支持涵盖了相对较少的语言集(当然包括英语)。

对于 IE 9 上的自动断字,您需要使用服务器端编程断字,或者更简单的客户端断字,以及诸如 Hyphenator.js 之类的工具

于 2013-03-07T04:47:18.943 回答
12

-ms-hyphens属性仅适用于 IE10+。在 IE9 或更低版本中是不可能的。

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

它还不能在 Chrome 中工作:WebKit Hyphenation

于 2013-03-07T02:01:47.657 回答
12

如果浏览器支持 & 语言包括连字符字典,则插入连字符。但是你的

aaaaaaaaaaaaaaaaaa

不在字典里。

因此,您必须像在https://jsfiddle.net/LJYj3/5/&shy;中那样插入您满意的软连字符

这里有更多值得思考的地方:https ://stackoverflow.com/a/856322/1696030

于 2013-03-07T02:05:30.323 回答
0

我找不到任何 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(" ");
  }
于 2021-06-09T17:47:48.277 回答