Home » Questions » Computers [ Ask a new question ]

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

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

"Given a relatively simple CSS:

div {
width: 150px;
}
<div>
12333-2333-233-23339392-332332323
</div>
Run code snippetHide resultsExpand snippet

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?"

Asked by: Guest | Views: 160
Total answers/comments: 4
Guest [Entry]

"Replace your hyphens with this:

­

It's called a ""soft"" hyphen.

div {
width: 150px;
}
<div>
12333­2333­233­23339392­332332323
</div>
Run code snippetHide resultsExpand snippet"
Guest [Entry]

"In all modern browsers* (and in some older browsers, too), the <wbr> element is the perfect tool for providing the opportunity to break long words at specific points.

To quote from that link:

The Word Break Opportunity (<wbr>) HTML element represents a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.

Here's how it could be used to in the OP's example (or see it in action at JSFiddle):

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

*I've tested it in IE9, IE10, and the latest versions of Chrome, Firefox, and Opera, and Safari.

div {
width: 150px;
}
<div>
12333-<wbr>2333-<wbr>233-<wbr>23339392-<wbr>332332323
</div>
Run code snippetHide resultsExpand snippet"
Guest [Entry]

As part of CSS3, it is not yet fully supported, but you can find information on word-wrapping here. Another option is the wbr tag, ­, and ​ none of which are fully supported either.
Guest [Entry]

"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 ­ 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."