Wednesday, September 18, 2013

Fix to prevent line breaks at hyphens in HTML

The problem

When writing HTML you may want to include something like a phone number in the form 1-800-555-1212. The problem is that this might be displayed as:
... 1-800-555-
1212...
This is probably not what you want - you'd prefer the entire thing to appear on one line.

Solution(s)

Non-breaking Hyphen

This is the most obvious logical solution - we have non-breaking spaces ( ) so all we need is a non-breaking hyphen, right? Well, not quite.
First, there is no standard entity for a non-breaking hyphen. Instead, this is a character defined in the Unicode specification as character #8209. If you want to use this in your HTML you can use either ‑ or ‑. The problem here is the font - most fonts probably don't include this character and will render it as some box with either digits or punctuation inside. What other options are there?


CSS white-space

This is the most correct answer. It requires two steps. First, define a CSS class:
.nobreak { white-space: nowrap; }
Then use it your HTML as:
<p>Lorem ipsum <span class="nobreak">1-800-555-1212</span>.</p>
The especially nice thing about this is that it's generic and will work equally well with:
<p>Dolor amit <span class="nobreak">1 (800) 555-1212</span>.</p>


My hack: super-under

And just in case you're curious what kind of craziness I can come up with, here's my third possible solution:
<p>Sibiliy si emgo: 1<sup>_</sup>800<sup>_</sup>555<sup>_</sup>1212.</p>
Yes, that's right: Take an underscore character ('_') and superscript it. A work of genius I say ...

No comments:

Post a Comment

Some HTML tags are accepted, SomeLink, bold and italic seem to be it.