css word wrap that wraps whole word without breaking them?

Eddy picture Eddy · May 1, 2014 · Viewed 49.2k times · Source

I need to fit a long text to a width of about 300 pixels. I'm using this css:

 div {      
      width: 300px;
      color:white;
      word-wrap:break-word;
      }

My issue is with the word-wrap:break-word;. It's breaking words in the middle of the word. But what I need is to have the words stay as they are, and for the document to be smart enough to break the line when appropriate, and keep the words themselves intact.

Is that possible? I tried every option of word-wrap but nothing works. Either the paragraphs are not breaking and the text stays off screen, or the words break and a couple of letters are in one line, while other letters are in the following line.

EDIT: adding my code to form a concrete example. My entire style element:

<style type="text/css">
    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px OpenSansHebrew-Regular}
    p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 10.0px OpenSansHebrew-Regular; min-height: 12.0px}

div {
    width: 300px;
    color:white;
    font-size:10px;
    word-wrap:break-word;
}

pre {white-space:break;}

</style>

Then in the body element:

<body bgcolor="#1fa0e2">
<p class="p1">
<div>
<bdo dir="rtl">
<pre>
    דירת 3 חדרים ברחוב ארתור רובינשטיין בתל אביב הוצעה באחרונה למכירה ב–2.5 מיליון שקל, ובסופו של דבר נמכרה ב–2.195 מיליון בלבד - פער של 12% בין המחיר המבוקש למחיר המכירה. בירושלים, דירת 4 חדרים ברחוב צביה יצחק הוצעה למכירה ב–1.6 מיליון שקל ונמכרה ב–40% פחות - 950 אלף שקל בלבד.

</pre>
</div>
</bdo>
<span class="Apple-converted-space"> </span></p>

</body>
</html>

Answer

GolezTrol picture GolezTrol · May 1, 2014

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/