Paragraphs & wrapping

white-space-collapse

white-space-collapse sets whether runs of spaces and line breaks written in the HTML collapse into one, or stay as written. It is the part of white-space that does not cover wrapping.

Syntax

collapse | preserve | preserve-breaks | preserve-spaces | break-spaces

Preview

The quick brown fox jumps over the lazy dog. 素早い茶色の狐がのろまな犬を飛び越える。
Presets
Drag the bottom-right corner to resize

Code

.box {
  white-space-collapse: preserve;
}

Controls

white-space-collapsepreserve
white-space-collapse
The quick brown fox jumps over the lazy dog. 素早い茶色の狐がのろまな犬を飛び越える。

About

What the values mean

  • collapse: the initial value. Runs of spaces and line breaks collapse into a single space, and spaces at the start and end of lines are removed.
  • preserve: keeps spaces and line breaks as written.
  • preserve-breaks: keeps line breaks only, and collapses runs of spaces into one.
  • preserve-spaces: keeps spaces as written, and turns line breaks and tabs into a single space each. This matches xml:space="preserve" in SVG. Only Firefox supports it.
  • break-spaces: almost the same as preserve, but spaces left at the end of a line also take up room, and lines can wrap between spaces.

The preview text has three spaces between the words of the first line, an indent of four spaces at the start of the second line, and two line breaks. With preserve it stays as written, with preserve-breaks only the spaces collapse, and with collapse the line breaks go too and the text runs together as one sentence. break-spaces only differs when there are spaces at the end of a line, so this text looks the same as with preserve.

When to use it

Use it to show text typed into a form with its line breaks (preserve-breaks), or to keep the indentation of code (preserve). Unlike white-space, it does not change whether lines wrap, so you can change how spaces are handled and leave the wrapping alone.

Watch out

  • white-space is a shorthand for white-space-collapse and text-wrap-mode (whether lines wrap). white-space: pre-wrap handles spaces like preserve, and white-space: pre-line like preserve-breaks. A later white-space overrides this property too.
  • It is inherited, so setting it on the box also affects the text of the elements inside.
  • Supported from Chrome and Edge 114, Firefox 124, and Safari 17.4. The spec also has discard, which removes all spaces and line breaks, but no browser supports it, so it is left out of the syntax and the buttons.

Comments