css word wrap that wraps whole word without breaking them?

…衆ロ難τιáo~ 提交于 2019-12-02 18:58:00

You don't need to do anything special. Normally the text will break between words.

If that doesn't happen, then

  1. either the container is too wide
  2. the container is explicitly set to not break on spaces at all. For instance if it is a <pre> element, or has the css white-space:pre; or white-space:nowrap;.
  3. the text contains non-breaking spaces (&nbsp;) instead of normal spaces.

Solution: use

white-space: pre-wrap;

It will make the element behave like a pre element, except it also wraps when the line is too long. See also: http://css-tricks.com/almanac/properties/w/whitespace/

I was messing about with this. People didn't mention setting the word-break style too. The default word-break rules must wrap the word at the end of the container space, but doesn't keep the word intact.

So the solution to your problem in CSS would be:

pre{
    white-space: pre-wrap;
    word-break: keep-all; /*this stops the word breaking*/
}

Edit: I was messing with this further and because I'm using bootstrap, their styling seems to mess with pre tag a lot. Use the !important keyword to override their styling.

You can wrap the word with a <span> tag and add either white-space: nowrap or display: inline-block.

Note:: Make sure your data doesn't read like.. word&nbsp;word&nbsp;word or browsers other than chrome think its one word

Sounds crazy but a bug in our companys mobile app was doing this and till I checked our API data I thought the internet had broken :p

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