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

Viewed 18341

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.

5 Answers

Without HTML5, you can use Javascript to insert <span></span> before or after the characters you want to break on:

//Jquery
$("#id_of_the_container").html(function(index, text) {
    return text.replace(/_/g, "_<span />");
});

//Pure Javascript
var htmlText = document.getElementById("id_of_the_container").innerHTML;
document.getElementById("id_of_the_container").innerHTML = htmlText.replace(/_/g, "_<span />");

then use the CSS class of the container to wrap the words :

.yourClass {
    word-break : break-word;
}

and finally set a zero pixel wide white space as the content before the span :

.yourClass > span:before {
    content: "\200b";
}

$("#set").html(function(index, text) {
  return text.replace(/_/g, "_<span />");
});
.boxes-container > div {
  margin: 5px;
  max-width: 200px;
  border : solid black 2px;
  display: inline-block;
  padding : 5px;
}

.bigger {
  margin-right : 200px !important;
}

.wrap {
  word-break: break-word;
}

.wrap > span:before {
  content : "\200b";
}

.answer-example {
  color : RGB(0, 50, 0);
  border-color: RGB(0, 50, 0) !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="boxes-container">
  <div class="bigger">
    Without_Anything,
    Long_Strings_With_Underscores_Make_text_Hard_To_Wrap
  </div>
  <div class="wrap">
    Without_Span_tags,
    Long_Strings_With_Underscores_Make_text_Hard_To_Wrap
  </div>
  <div id="set" class="wrap answer-example">
    With_Span_tags,
    Long_Strings_With_Underscores_Make_text_Hard_To_Wrap
  </div>
</div>

Related