πŸ“„ CSS Tutorial: white-space

πŸ“Œ Introduction

The white-space property in CSS controls how whitespace inside an element is handled β€” including spaces, tabs, and line breaks. It plays a crucial role in formatting text, controlling wrapping, and preserving the structure of preformatted content. Mastering this property gives you full control over how text behaves inside containers. ✨

🎯 Why Use white-space?

  • To preserve formatting in code blocks or poems πŸ“œ
  • To control whether text wraps or not πŸ”€
  • To keep multiple spaces visible (instead of collapsing) 🧩
  • To implement chat bubbles, labels, and UI elements cleanly πŸ’¬

✨ Syntax

Basic Syntax

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

🧩 Available Values

1. normal (default)

Collapses whitespace and wraps text when necessary. Most block elements use this by default.

2. nowrap 🚫

Collapses whitespace but prevents text from wrapping β€” all content stays on one line.

nowrap Example

.nowrap {
  white-space: nowrap;
}

3. pre πŸ“

Preserves whitespace and line breaks exactly as in the HTML β€” just like the<pre> tag.

pre Example

.code-block {
  white-space: pre;
}

4. pre-wrap πŸ“¦

Preserves whitespace but still allows text to wrap when needed. Useful for user-generated content, chat messages, comments.

pre-wrap Example

.chat {
  white-space: pre-wrap;
}

5. pre-line πŸ“˜

Collapses spaces but preserves line breaks. Ideal when you want compact text but want to keep newlines from user input.

pre-line Example

.notes {
  white-space: pre-line;
}

6. break-spaces 🧨 (Modern)

Like pre-wrap, but whitespace is preserved and lines won't collapse even if long sequences occur. Great for aligning ASCII art or special layouts.

break-spaces Example

.ascii-art {
  white-space: break-spaces;
}

πŸ”₯ Practical Examples

1. Prevent Text Wrapping for Buttons

Button Example

button {
  white-space: nowrap;
}

2. Display Poem or Code with Preserved Formatting

Preformatted Text

pre.poem {
  white-space: pre;
  font-family: monospace;
}

3. Chat Bubble Layout

Chat Example

.bubble {
  white-space: pre-wrap;
  max-width: 280px;
}

πŸ“Š Comparison Table

ValuePreserve Spaces?Preserve Line Breaks?Wrap Text?
normalNoNoYes
nowrapNoNoNo
preYesYesNo
pre-wrapYesYesYes
pre-lineNoYesYes
break-spacesYes (including trailing)YesYes

πŸ–ΌοΈ Visual Example

>>β€œWhitespace is not just empty space β€” it’s a crucial part of good design.” ✨

πŸŽ‰ Conclusion

The white-space property gives you full control over how spaces and newlines are handled inside text elements. Whether you're building text editors, chat apps, article layouts, or code blocks, mastering this property will elevate your CSS typography and layout skills. πŸš€