Hoylen's Weblog

Thu, 28 Jan 2010

Controlling URL line breaking with zero-width spaces

Line breaks for URLs often occur where you don't want them to. The solution is to use a zero-width space to suggest where it could have a line break.

In HTML, a zero width space can be represnted as "​". This character must only be used in the displayed URL and not the URL in the href attributes.

Here are two examples. The first URL is unmodified. The second URL uses zero width spaces after the slashes and uses non-breaking hyphens. Resize the browser window to see how the line breaking behaves.



Looks good, but there is one big disadvantage: if someone copies-and-pastes the URL it will not work. This is less of a problem if the URL is a hyperlink which they will normally click, but it is something to keep in mind.

The same trick can be used in Word documents. There are many ways to enter a zero-width space in Microsoft Word, but they are all very complicated. Instead, I think the simplest way is to copy it from another document. For example, save this Web page as HTML, open it in Microsoft Word, turn on hidden symbols, and copy the zero-width space character from it. With hidden symbols turned on, the zero-width space appears as a rectangle inside a rectangle. Or create a simple HTML document with ​ in it.

However, do not use non-breaking hyphens to further control the line breaks. If someone copies-and-pastes the URL, it will not work when there are non-breaking hyphens in it. They will be very confused, because the hyphen looks correct even though it is the wrong character.