Discretionary line break in HTML?

荒凉一梦 提交于 2019-12-04 00:49:31

To indicate where line break should not appear between words, use a NO-BREAK SPACE, or ' `, between words. Any normal space is breakable. So you can write e.g.

Hello, my name is foo. 

If you would rather indicate the allowed breaks (as per your comment below), you can wrap the text inside a nobr element (nonstandard, but works like a charm) or inside any element for which you set white-space: nowrap, thereby disallowing line breaks except when explicitly forced or allowed. You would then use the <wbr> tag (nonstandard, but...) or the character reference &#8203; or &#x200b; (for ice ZERO WIDTH SPACE) after a space to allow a line break, e.g.

<nobr>Hello, <wbr>my name <wbr>is foo.</nobr>

The choice between <wbr> and ZERO WIDTH SPACE is a tricky issue, mainly due to IE oddities.

chrisbulmer

You could use the <wbr> tag.

EDIT: As mentioned in the comments, you could use a zero-width space: &#8203; (See also: What's the opposite of a nbsp?)

I don't think there's any native way to do that, but here's a hack I've been using whenever I really need this sort of thing:

var str = "Hello,<br>My name is foo.";

str = str.replace(/ /g, '&nbsp;').replace(/<br>/g, ' ');

Basically, use a non-breaking space to separate the words you don't want to break at.

See it here in action: http://jsfiddle.net/5xmt6/ (resize the window to see how it reacts).


Note: this is very hacky, and introduces its own set of problems; namely: if the viewport becomes extremely narrow, the rest of the text won't wrap.

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