有时,很长的文本字符串可能会溢出布局的容器。
例如:
这是所有涉及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
。 闪烁(经过测试的Chrome v45)将采用其中一种。 - 单独使用
overflow-wrap
时,单词会在需要的任何地方中断。 如果有一个“可接受的中断”字符(例如,像破折号一样),它将在此处中断,否则它将执行所需的操作。 - 您也可以使用
hyphens
,因为如果浏览器支持,连字符会尝试在连字符处添加连字符(Firefox在编写时不支持闪烁)。 -
word-break: break-all;
告诉浏览器可以在任何需要的地方打断单词。 即使这样做还是可以的,所以我不确定在什么情况下100%必要。
如果您希望使用连字号更加手动,则可以在标记中建议它们。 在MDN页面上查看更多信息 。
浏览器支持
对于word-break
:
该浏览器支持数据来自Caniuse ,其更多信息。 数字表示浏览器支持该版本及更高版本的功能。
桌面
铬 | 火狐浏览器 | IE浏览器 | 边缘 | 苹果浏览器 |
---|---|---|---|---|
44 | 15 | 5.5 | 12 | 9 |
手机/平板电脑
Android Chrome浏览器 | Android Firefox | 安卓系统 | iOS Safari |
---|---|---|---|
81 | 68 | 81 | 9.0-9.2 |
对于hypens
:
该浏览器支持数据来自Caniuse ,其更多信息。 数字表示浏览器支持该版本及更高版本的功能。
桌面
铬 | 火狐浏览器 | IE浏览器 | 边缘 | 苹果浏览器 |
---|---|---|---|---|
86 | 6 * | 10 * | 12 * | 5.1 * |
手机/平板电脑
Android Chrome浏览器 | Android Firefox | 安卓系统 | iOS Safari |
---|---|---|---|
81 | 68 | 81 | 4.2-4.3 * |
对于overflow-wrap
:
该浏览器支持数据来自Caniuse ,其更多信息。 数字表示浏览器支持该版本及更高版本的功能。
桌面
铬 | 火狐浏览器 | IE浏览器 | 边缘 | 苹果浏览器 |
---|---|---|---|---|
23 | 49 | 11 | 18岁 | 6.1 |
手机/平板电脑
Android Chrome浏览器 | Android Firefox | 安卓系统 | iOS Safari |
---|---|---|---|
81 | 68 | 4.4 | 7.0-7.1 |
对于text-overflow
:
该浏览器支持数据来自Caniuse ,其更多信息。 数字表示浏览器支持该版本及更高版本的功能。
桌面
铬 | 火狐浏览器 | IE浏览器 | 边缘 | 苹果浏览器 |
---|---|---|---|---|
4 | 7 | 6 | 12 | 3.1 |
手机/平板电脑
Android Chrome浏览器 | Android Firefox | 安卓系统 | iOS Safari |
---|---|---|---|
81 | 68 | 2.1 | 3.2 |
防止椭圆形溢出
可以考虑的另一种方法是将文本全部截断并在文本字符串到达容器的位置添加省略号:
.ellipses {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
使用text-overflow
是它得到了普遍支持 。
例子
请参阅CodePen上CSS-Tricks( @ css-tricks ) 编写的Pen Hyphenate Long Words 。
见笔椭圆通过CSS-技巧( @ CSS-技巧上) CodePen 。
请参阅CodePen上的Chris Coyier ( @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;
}
翻译自: https://css-tricks.com/snippets/css/prevent-long-urls-from-breaking-out-of-container/