Long have I been looking for a way to break long strings of letters over multiple lines in a good way. None of the
CSS inline or
HTML/CSS <span> examples I have found have been able to automatically apply to long links or file names. I have found this a special pain when dealing with development for Growl due to the narrow width and often found long file names or URL:s often passed as message content.
For example, let us say you have a 300 pixels wide column but have to write a URL or two there. It will look like this with
Take a look at https://lynks.se/interaktion/super_long_url/improved_line_breaks_in_html_without_touching_your_markup, it’s good.
And like this with
Or like this where you manually have to split the string into separate
<span>:s with added CSS rules to avoid ugly spaces, a method that is also not especially nice to search engines or screen readers:
Take a look at https://lynks.se/interaktion/ super_long_url/ improved_ line_ breaks_ in_ html_ without_ touching_ your_ markup, it’s good.
There has to be a better way
To the rescue comes the
<wbr /> tag which is a behavioral and in a sense optional tag for web browsers which essentially says ”it’s okay to break here if you want”, not unlike like a hyphen. Which means some browsers will interpret it slightly different, but as long as we can get a good way to break these long links and filenames we will be happy.
Adding a few such tags to our example will give the desired result:
Take a look at https://lynks.se/
So, we can now use the
join code to easy accomplish what we are looking for to add a line break after a slash:
document.getElementsByTagName(changeThisElement)[i].innerHTML = indata[i].innerHTML.split("/").join("/
The Complete Code
This goes in the
<head> tag of your document:
As far as I am aware there is only one problem with the
<wbr /> tag which is the lack of hyphens in some cases. If you know a way to set a hyphen only when the browser choose to use the
<wbr /> tag I will be more than happy to hear from you. This should work in Safari 2, Firefox 2, Opera 9 and Internet Explorer 6 including later versions of these browsers.