DEV Community

Cover image for CSS white-space Property Explained
Arbaoui Mehdi
Arbaoui Mehdi

Posted on

CSS white-space Property Explained

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Preserve the white space, and allows text wrapping.

Alt Text

pre-line

h1 {
  white-space: pre-line;
}
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

Top comments (1)

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

I love hate whitespace property.

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