处理长单词和 URL(强制换行、连字符、省略号等)

Avatar of Chris Coyier
Chris Coyier

有时,非常长的文本字符串可能会超出布局容器的范围。

例如

URL 通常不包含空格,因此它们通常是罪魁祸首。

这是一个包含所有相关 CSS 属性的大片段代码

.dont-break-out {

  /* These are technically the same, but use both */
  overflow-wrap: break-word;
  word-wrap: break-word;

  -ms-word-break: break-all;
  /* This is the dangerous one in WebKit, as it breaks things wherever */
  word-break: break-all;
  /* Instead use this non-standard one: */
  word-break: break-word;

  /* Adds a hyphen where the word breaks, if supported (No Blink) */
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;

}

这将为我们解决问题

以下是要点

  • overflow-wrap: break-word; 确保长字符串会换行,而不是超出容器。您也可以使用 word-wrap,因为规范中说明,它们实际上只是彼此的替代名称。一些浏览器支持其中一个,而不支持另一个。Firefox(测试版本 v43)仅支持 word-wrap。Blink(测试版 Chrome v45)可以接受这两个名称。
  • 仅使用 overflow-wrap 时,单词会在需要换行的地方换行。如果存在“可接受的换行符”(例如文字短划线),则会在该处换行,否则它会根据需要进行换行。
  • 您也可以使用 hyphens,因为它会在浏览器支持的情况下尝试在换行处巧妙地添加连字符(在撰写本文时,Blink 不支持,Firefox 支持)。
  • word-break: break-all; 用于告诉浏览器可以在任何需要的地方换行。尽管它无论如何都会这样做,所以我不知道在哪些情况下它 100% 必要。

如果您想更手动地使用连字符,可以在标记中建议它们。查看MDN 页面上的更多信息

浏览器支持

对于 word-break

这些浏览器支持数据来自Caniuse,其中包含更多详细信息。数字表示浏览器在该版本及更高版本中支持该功能。

桌面

ChromeFirefoxIEEdgeSafari
44155.5129

移动/平板电脑

Android ChromeAndroid FirefoxAndroidiOS Safari
1271271279.0-9.2

对于 hypens

这些浏览器支持数据来自Caniuse,其中包含更多详细信息。数字表示浏览器在该版本及更高版本中支持该功能。

桌面

ChromeFirefoxIEEdgeSafari
886*10*12*5.1*

移动/平板电脑

Android ChromeAndroid FirefoxAndroidiOS Safari
1271271274.2-4.3*

对于 overflow-wrap

这些浏览器支持数据来自Caniuse,其中包含更多详细信息。数字表示浏览器在该版本及更高版本中支持该功能。

桌面

ChromeFirefoxIEEdgeSafari
234911186.1

移动/平板电脑

Android ChromeAndroid FirefoxAndroidiOS Safari
1271274.47.0-7.1

对于 text-overflow

这些浏览器支持数据来自Caniuse,其中包含更多详细信息。数字表示浏览器在该版本及更高版本中支持该功能。

桌面

ChromeFirefoxIEEdgeSafari
476123.1

移动/平板电脑

Android ChromeAndroid FirefoxAndroidiOS Safari
1271272.13.2

使用省略号防止溢出

另一种需要考虑的方法是完全截断文本,并在文本字符串到达容器时添加省略号

.ellipses {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

使用 text-overflow 的好处在于它得到普遍支持

示例

查看 CSS-Tricks 的 CodePen 上的笔 Hyphenate Long Words@css-tricks)。

查看 CSS-Tricks 的 CodePen 上的笔 Ellipses@css-tricks)。

查看 Chris Coyier 的 CodePen 上的笔 Figuring Out Line Wrapping@chriscoyier)。

更多资源

对于 SCSS 爱好者

这些通常是您根据需要散布到代码中的内容,因此它们可以作为不错的 @mixins

@mixin word-wrap() {
  overflow-wrap: break-word;
  word-wrap: break-word;
  -ms-word-break: break-all;
  word-break: break-all;
  word-break: break-word;
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}
@mixin ellipsis() {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}