white-space

Term side of the Card.
Topic: Text Handling
Unit title: white-space
Categories: Property
Explanation side of the Card

Explanation: The property that controls how white space inside an element is handled. It can be set to 'normal', 'nowrap', 'pre', 'pre-wrap' or 'pre-line', affecting whether text wraps, is preserved or collapses whitespace.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 1.
Availability: 

Example

Wrongcss
.comment-body {
  white-space: pre;
}
Rightcss
.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: pre for 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 overflow handling or text-overflow.
  • Code blocks that must not wrap have overflow-x: auto so 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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy