html (+css): denoting a preferred place for a line break

Jason S picture Jason S · Mar 22, 2011 · Viewed 31.9k times · Source

Let's say I have this text that I want to display in an HTML table cell:

Honey Nut Cheerios, Wheat Chex, Grape-Nuts, Rice Krispies, Some random cereal with a very long name, Honey Bunches of Oats, Wheaties, Special K, Froot Loops, Apple Jacks

and I want the line to break preferentially after one of the commas.

Is there a way to tell the HTML renderer to try breaking at some designated spot, and do that first before trying to break after one of the spaces, without using non-breaking spaces? If I use non-breaking spaces then it makes the width larger unconditionally. I want the line break to happen after one of the spaces, if the line-wrapping algorithm has tried it with the commas first and can't get the line to fit.

I tried wrapping text fragments in <span> elements but that doesn't seem to do anything helpful.

<html>
  <head>
      <style type="text/css">
        div.box { width: 180px; }
        table, table td { 
          border: 1px solid; 
          border-collapse: collapse; 
        }
      </style>
  </head>
  <body>
    <div class="box">
      <table>
      <tr>
          <td>lorem ipsum</td>
          <td>lorem ipsum</td>
          <td>lorem ipsum</td>
      </tr>
      <tr>
          <td>lorem ipsum</td>
          <td>
            <span>Honey Nut Cheerios,</span>
            <span>Wheat Chex,</span>
            <span>Grape-Nuts,</span>
            <span>Rice Krispies,</span>
            <span>Some random cereal with a very long name,</span>
            <span>Honey Bunches of Oats,</span>
            <span>Wheaties,</span>
            <span>Special K,</span>
            <span>Froot Loops,</span>
            <span>Apple Jacks</span>
          </td>
          <td>lorem ipsum</td>
      </tr>
      </table>
    </div>
  </body>
</html>

note: It looks like the CSS3 text-wrap: avoid behavior is what I want, but I can't seem to get it to work.

Answer

Eggert J&#243;hannesson picture Eggert Jóhannesson · Apr 11, 2012

By using

span.avoidwrap { display:inline-block; }

and wrapping the text I want to be kept together in

<span class="avoidwrap"> Text </span>

it will wrap first in preferred blocks and then in smaller fragments as needed.