You could use one of these two CSS properties:
-
word-break
(with the value break-all
): indicates whether the browser should include line breaks where the word exceeds the size of the container.
-
overflow-wrap
(with the value break-word
): indicates whether the browser should include Line breaks within a word if you are going to exceed the size of the container.
As you can see, the two are quite similar. The main difference is that overflow-wrap
will only create the line break within a word if the whole word does not enter a line (if not, the jump will put it in the space with the previous word), which makes the sentences Be more "natural" by not breaking the words unless it is strictly necessary.
Instead break-word
will break the word when it reaches the end of the line, regardless of whether it would have entered the entire line (giving a justified alignment effect, but breaking the words less naturally).
One problem is that it is not supported by the Edge browser (neither, nor overflow-wrap
nor word-break
) and that many mobile browsers do not support well word-break
(visit links to see support tables).
Here you can see an example:
document.querySelector("button").addEventListener("click", function() {
var texto = prompt("Escribe algo");
var p = document.createElement("P");
var t = document.createTextNode(texto);
p.appendChild(t);
document.getElementById("div").appendChild(p);
});
#div {
width: 300px;
height: 200px;
overflow-y: scroll;
border:1px solid gray; /* para visualizar mejor la caja */
overflow-wrap: break-word;
}
<button>Agrega texto</button>
<div id="div"></div>