To add some info on @Explosion Pills correct answer and extract some info from MDN:
The CSS white-space
attribute is there to help:
pre:
white-space: pre
Sequences of white space are preserved. Lines are only broken at
newline characters in the source and at <br>
elements.
This might result in unwanted horizontal scrollbars as shown in the example!
pre-wrap:
white-space: pre-wrap
Sequences of white space are preserved. Lines are broken at newline
characters, at <br>
, and as necessary to fill line boxes.
As @ceremcem pointed out the line breaks at the end of the box will not be transferred when the text is copy-pasted, which makes sense since these line breaks are not part of the text formatting but rather of the visual appearence.
pre-line:
white-space: pre-line
Sequences of white space are collapsed. Lines are broken at newline
characters, at <br>
, and as necessary to fill line boxes.
div{
border: 1px solid #000;
width:200px;
}
.pre {
white-space: pre;
}
.pre-wrap{
white-space: pre-wrap;
}
.pre-line{
white-space: pre-line;
}
.inline-block{
display:inline-block
}
<h2>
pre
</h2>
<div class="pre" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
<h2>
pre-wrap
</h2>
<div class="pre-wrap" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
<h2>
pre-line
</h2>
<div class="pre-line" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
<h2>
Chrome FIX
</h2>
<div class="pre-line inline-block" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
EDIT 08/14/2018:
In Chrome you might experience troubles: Pressing Enter will generate a new <div>
inside your contenteditable. To prevent that you can either press Shift+Enter or set display: inline
to the contenteditable <div>
as seen in the fiddle.