How to break word after special character like Hyphens (-)

Viewed 21600

Given a relatively simple CSS:

div {
  width: 150px;
}
<div>
  12333-2333-233-23339392-332332323
</div>

How do I make it so that the string stays constrained to the width of 150, and wraps to a new line on the hyphen?

11 Answers

Replace your hyphens with this:

&shy;

It's called a "soft" hyphen.

div {
  width: 150px;
}
<div>
  12333&shy;2333&shy;233&shy;23339392&shy;332332323
</div>

Your example works as expected in Google Chrome, Safari (Windows), and IE8. The text breaks out of the 150px box in Firefox 3 and Opera 9.5.

Additionally &shy; won't work for your example, as it will either:

  • work when word-breaking but when not word-breaking not display any hyphens, or

  • work when not word-breaking but display two hyphens when word-breaking since it adds a hyphen on a break.

In this specific instance (where your string is going to contain hyphens) I'd transform the text to this server-side:

<div style="width:150px;">
  <span>12333-</span><span>2333-</span><span>233-</span><span>23339392-</span><span>332332323</span>
</div>

You can use 0 width space after hyphen character:

div {
  width: 150px;
}
<div>
  12333-&#8203;2333-&#8203;233-&#8203;23339392-&#8203;332332323
</div>

if You want line break before hyphen use &#8203;- instead.

Related