π 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
| Value | Preserve Spaces? | Preserve Line Breaks? | Wrap Text? |
|---|---|---|---|
| normal | No | No | Yes |
| nowrap | No | No | No |
| pre | Yes | Yes | No |
| pre-wrap | Yes | Yes | Yes |
| pre-line | No | Yes | Yes |
| break-spaces | Yes (including trailing) | Yes | Yes |
πΌοΈ Visual Example
Further details can be found at: https://dummyimage.com/900x260/eeeeee/000000&text=white-space+demo
π 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. π