Smarter word break in CSS?

百般思念 提交于 2019-12-03 05:26:31

问题


If I just put word-break: break-all on an element, I often end up with this:

Hello people, I am typing a mes
sage that's too long to fit!

Obviously this would be much better as:

Hello people, I am typing a
message that's too long to fit!

But at the same time if someone writes:

BLAAAAAAAAARRRRRRRRRRRRGGGGGGGGHHHHHHHH!!!!!!

Then I'd want it to be:

BLAAAAAAAAARRRRRRRRRRR
RGGGGGGGGHHHHHHHH!!!!!!

I can't seem to find a way to actually do this.

Note that the width of the element is not fixed and may change.


回答1:


Try word-break: break-word; it should behave as you expect.




回答2:


For a lot of our projects we usually add this where necessary:

.text-that-needs-wrapping {
    overflow-wrap: break-word;
    word-wrap: break-word;
    -ms-word-break: break-all;
    word-break: break-word;
    -ms-hyphens: auto;
    -moz-hyphens: auto;
    -webkit-hyphens: auto;
    hyphens: auto;
}

It handles most odd situations with different browsers.




回答3:


For smart word breaks, or for correct word breaks in the first place, you need language-dependent rules. For English and many other languages, the correct breaking means hyphenation, with a hyphen added at the end of a line when a break occurs.

In CSS, you can use hyphens: auto, though you mostly still need to duplicate it using vendor prefixes. As this does not work on IE 9, you may consider JavaScript-based hyphenation like Hyphenate.js instead. In both cases, it is essential to use language markup (lang attribute).

Breaking long, unhyphenateable strings is a different issue. They would best be handled in preprocessing, but in a simple setting, word-break: break-word (which means incorrect breaking of words, in English for example) may be considered as an emergency.



来源:https://stackoverflow.com/questions/12699800/smarter-word-break-in-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!