CSS word wrap / line break on underscores in addition to whitespace and hyphens

dsmtoday picture dsmtoday · Jun 11, 2011 · Viewed 14.2k times · Source

I have a bunch of really long file names that cause my HTML formatting to overflow. All of these filenames use underscores instead of spaces and would break/wrap easily if they were spaces. Like this.

Here_is_an_example_of_a_really_long_filename_that_uses_underscores_instead_of_spaces.pdf

Is there some way to tell CSS to treat underscores in text as if they were whitespace or hyphens, and thus wrap/break on underscores too? Like this.

Here_is_an_example_of_a_really_long_
file_name_that_uses_underscores_
instead_of_spaces.pdf

For my purposes, I cannot use a script to do this. I also don't want to use the word-wrap:break-word trick because that usually doesn't work without also specifying a width. Also, it breaks arbitrarily in the middle of words.

Thanks.

Answer

Keltex picture Keltex · Jun 11, 2011

You can use the <wbr> tag (http://www.quirksmode.org/oddsandends/wbr.html) which lets the browser break whereever you place it.

So your HTML should be:

Here_<wbr>is_<wbr>an_<wbr>example_<wbr>of_<wbr>a_<wbr>really_<wbr>...

You can add this tag on the server-side before you output the HTML.

An alternative is the entity &#8203; which is a zero width space. Sometimes this works better on certain browsers.