The correct way to do word wrapping (breaking) by using CSS rules

You often have to deal with words that are too long and they possible do not fit as a whole inside an HTML element. In such cases you have to break the word and put the part that does not fit in the next line. On the other side, you do not want to always fill the lines of an HTML element with text, which means that you do not want to break every single word, but instead you only want to break the words that are wider than the width of the containing HTML element.

If that is the case, the CSS command you are searching for is the following: word-wrap: break-word

You might also come over the word-break: break-all command. However, using this rule, you are telling CSS to break all words, so that every line of your HTML element is filled with text.

Do not forget that when using the word-wrap: break-word rule you have to define the width of your HTML element, so that CSS knows if and where to break a long word. The width can be either a fixed value or a percentage.

You can find a simple example in my GitHub repository. In this example the following divs were used:

  1. No wrapping rule is defined and the text fits into the HTML element

  2. A very long word breaks the User interface, even when the width of the containing HTML element is defined

  3. The word-wrap: break-word is used and the long word is wrapped to the next line

  4. The word-wrap: break-word is used with normal text. No weird wrapping happens and the text looks fine.

comments powered by Disqus