I'm a bit late to the party, but I think I found the answer.
I've always used word-break: break-word
because it's perfect in most cases, if there is enough space it wraps and keeps the words, and if there's not enough space it breaks the word. MDN Web Docs say that word-break: break-word
is deprecated but will probably still works, but the real reason I started looking at an alternative is that visual studio doesn't auto-complete break-word
anymore :)
Solution ?
MDN - overflow-wrap
overflow-wrap: anywhere;
Wraps the words to new line, and only breaks the word if it need to.
"The property was originally a nonstandard and unprefixed Microsoft extension called word-wrap, and was implemented by most browsers with the same name. It has since been renamed to overflow-wrap, with word-wrap being an alias."
So overflow-wrap
should be used instead of word-wrap
.
var s = document.querySelector('div');
function a(){
s.removeAttribute('class');
s.classList.add('a');
}
function b(){
s.removeAttribute('class');
s.classList.add('b');
}
#class{
border: 1px solid rgb(255, 120, 120);
width: 100px;
margin-top: 10px;
margin-bottom: 10px;
border-radius: 2px;
}
btn{
border: 1px solid gray;
padding: 2px;
border-radius: 5px;
box-shadow: 0 0 2px gray;
cursor: pointer;
}
.a{
overflow-wrap: normal;
}
.b{
overflow-wrap: anywhere;
}
<span>overflow-wrap:</span>
<btn onClick="a()">Normal</btn>
<btn onClick="b()">Anywhere</btn>
<div id='class'>
We need a very long word like Supercalifragilisticexpialidocious
</div>
<i>There's also overflow-wrap: break-word;</i>