DEV Community

loading...
Cover image for CSS white-space Property Explained

CSS white-space Property Explained

arbaoui_mehdi profile image Arbaoui Mehdi 🇲🇦 ・2 min read

When we add content to a specific HTML document, sometimes we add some unstructured content (eg: extra white spaces, breaks) that can't be displayed correctly in the browser.

Alt Text

As we see from the previous image that the browser by default doesn't render these extra spaces and breaks. However, if we want to handle that manually we can use the CSS property white-space which helps us to control the white spaces processing.

Following the possible combinations that can be used as a value of white-space:

normal

h1 {
  white-space: normal;
}

Render line break characters as a white space, excluding the <br> tag which will be rendered normally as single line break, then all the extra whitespaces will collapses into one space.

Alt Text

pre

h1 {
  white-space: pre;
}

Line breaks characters render normally, text will not be wrapped, plus the extra white spaces will be preserved.

Alt Text

nowrap

h1 {
  white-space: nowrap;
}

Behaves like normal value where it preserve the text to collapse, the text will not be wrapped except if we use a tag like the single line break <br>.

Alt Text

pre-wrap

h1 {
  white-space: pre-wrap;
}

Preserve the white space, and allows text wrapping.

Alt Text

pre-line

h1 {
  white-space: pre-line;
}

Extra white spaces are collapsed (form a single white space), line break preserved, and allows text wrapping.

Alt Text

Discussion (1)

pic
Editor guide
Collapse
adam_cyclones profile image
Adam Crockett • Edited

I love hate whitespace property.

Look ma it works, some time later.. oh it's overlapping.