HarshWombat HarshWombat - 3 months ago 9
CSS Question

Max-width not breaking single words, exceeding max-width

When using

max-width
why won't it "break" words that are longer than allowed and how would I go about making it work?

JSFiddle



function input() {
var inputText = document.getElementById("inputField").value;
document.getElementById("changingParagraph").innerHTML = inputText;
}

#changingParagraph {
max-width: 100px;
}

<input type="text" id="inputField" oninput="input()">
<p id="changingParagraph">
</p>




Answer

The <p> is not exceeding the max-width length that you have set. The issue is that the text is overflowing so it goes past the length you set for your element. There are a few different methods for breaking text to the next line.


Using overflow-wrap: break-word; (previously known as word-wrap: break-word):

  • will wrap overflowed words onto the the next line.
  • will only break a word if its length exceeds the length of the container.

function input() {
  var inputText = document.getElementById("inputField").value;
  document.getElementById("changingParagraph").innerHTML = inputText;
}
#changingParagraph {
  max-width: 100px;
  overflow-wrap: break-word;
}
<input type="text" id="inputField" oninput="input()">
<p id="changingParagraph">
</p>


Using word-break: break-all:

  • will break when the content hits the specified width, even if the text is a single word.

function input() {
  var inputText = document.getElementById("inputField").value;
  document.getElementById("changingParagraph").innerHTML = inputText;
}
#changingParagraph {
  max-width: 100px;
  word-break: break-all;
}
<input type="text" id="inputField" oninput="input()">
<p id="changingParagraph">
</p>


For the most readable and clean looking breaks, overflow-wrap: break-word; is the best option.