Latest Update
Incorporated the display:table
property for a cleaner solution. Check out the revised demo.
When it comes to wrapping text using CSS, you have the option to experiment with 3 different properties.
white-space
, word-break
, and word-wrap
More details available in the demo
Interactive Demo
p {
width: 100px;
border: 1px solid red;
}
.whiteSpace-Nowrap {
white-space: nowrap;
}
.whiteSpace-Normal {
white-space: normal;
}
.wordBreak-BreakAll {
word-break: break-all;
}
.displayTable {
display: table
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h5>{white-space: nowrap}</h5>
<p class='whiteSpace-Nowrap'>You might have <code>white-space:nowrap</code> which makes text ignore the border and continue going.</p>
<h5>{white-space: normal} or {word-break: normal} or {word-wrap: normal}</h5>
<p class='whiteSpace-Normal'>will make text wrap normally at the spaces between spaces. But if there's a long word like: supercalifragilisticexpialidocious that exceeds the width of it's container, it will only wrap at a hyphen. Sup-er-cal-i-fra-gil-is-tic-ex-pi-al-i-do-cious</p>
<hr>
<p style='border:0;width:100%;'>If you are having problems with long words, then you can use hyphens like the previous example, or try the following:</p>
<h5>{word-break: break-all} or {word-wrap: break-word}</h5>
<p class="wordBreak-BreakAll">breaks between any letters. It doesn't care where. So a word like: pneumonoultramicroscopicsilicovolcanoconiosis is chopped up and served in a thousand pieces.</p>
<hr>
<h5>{display:table}</h5>
<p class='displayTable'>behaves like a <table> so text will wrap and the container will expand vertically once text has reached it's limit horizontally.</p>
<p style='border:0;width:100%;'>The paragraph above and below have identical properties. The only difference between them is that the bottom paragraph has a long unbreakable word.</p>
<p class='displayTable'>A long word like: Antidisestablishmentarianism will not break out of the border. Instead, it will accommodate that unbreakable word by expanding.</p>
</body>
</html>