white-space
Example
.comment-body {
white-space: pre;
}.comment-body {
white-space: pre-wrap;
}'pre-wrap' keeps the user's spaces and line breaks but still wraps long lines inside the box.
Common mistakes
- Using
white-space: prefor comments and getting a horizontal scrollbar on long lines. - Setting 'nowrap' on a flex item and breaking the layout on small screens.
Key points
- User text with line breaks uses 'pre-wrap' or 'pre-line', not 'pre', so long lines still wrap.
- 'nowrap' text inside a narrow box is paired with
overflowhandling ortext-overflow. - Code blocks that must not wrap have
overflow-x: autoso they scroll instead of overflowing the page.
Interview questions
What is the difference between pre-wrap and pre-line?
'pre-wrap' keeps all spaces and line breaks. 'pre-line' keeps line breaks but collapses runs of spaces into one.
Is white-space a shorthand now?
Yes. In current specs it is a shorthand for white-space-collapse and text-wrap-mode, and the old keywords still work.
Why does white-space: nowrap not add an ellipsis?
'nowrap' only stops wrapping. An ellipsis also needs overflow: hidden and text-overflow: ellipsis.