tag white-space

📝 CSS white-space — Control How Whitespace is Handled in Text

The white-space property controls how spaces, tabs, and line breaks inside an element’s text are handled and displayed. This affects text wrapping, collapsing of spaces, and line breaks.


🔹 What Does white-space Do?

It lets you specify if and how whitespace characters are preserved, whether lines wrap or not, and how line breaks behave inside an element.


📘 Syntax

selector {
white-space: normal | nowrap | pre | pre-wrap | pre-line | break-spaces;
}

✅ Values Explained

ValueDescriptionBehavior
normalDefault. Collapses whitespace, allows lines to wrap.Multiple spaces → one space; text wraps at container edge.
nowrapCollapses whitespace, but prevents wrapping.Text stays on one line, may overflow container.
prePreserves whitespace and line breaks, no wrapping(like <pre>).Text respects all spaces and line breaks exactly as in source.
pre-wrapPreserves whitespace and line breaks, allows wrapping.Text wraps if too long but spaces and line breaks are preserved.
pre-lineCollapses whitespace, but preserves line breaks, allows wrapping.Multiple spaces collapsed, but line breaks honored.
break-spacesPreserves spaces, tabs, and line breaks; text wraps; spaces break lines.Spaces at line end wrap like normal text (CSS4 spec).

✍️ Examples

1. Normal vs Nowrap

<p style="white-space: normal;">
This text has multiple spaces but will collapse and wrap.
</p>

<p style="white-space: nowrap;">
This text will collapse spaces but won’t wrap and might overflow.
</p>

2. Preformatted Text

<pre style="white-space: pre;">
Line 1
Line 2 with indents
Line 3
</pre>

✅ Text preserves all spaces and line breaks.


3. Pre-wrap

<p style="white-space: pre-wrap;">
This text preserves spaces
and
line breaks but wraps too if needed.
</p>

🖼️ Image Idea: Whitespace Behavior Chart

Show side-by-side text blocks for each white-space value, highlighting:

  • How spaces are handled
  • Whether text wraps or not
  • Line breaks preservation

💡 Use Cases

  • normal: Regular paragraphs and most text.
  • nowrap: Prevent breaking in buttons, menus, or inline elements.
  • pre: Showing code snippets or ASCII art.
  • pre-wrap: Preserving user input formatting while wrapping nicely.
  • pre-line: Collapsing spaces but respecting new lines.
  • break-spaces: Advanced use for preserving spaces and wrapping with space breaks.

✅ Summary

Propertywhite-space
PurposeControl how whitespace and line breaks are handled
Default valuenormal
Key behaviorsCollapsing spaces, wrapping text, preserving line breaks
Use casesText formatting, code blocks, user input preservation

🔚 Final Thought

Mastering white-space lets you control how your text breathes and flows, ensuring readability and precise formatting — crucial for clean and accessible web design.