CSS `white-space`: Mastering Whitespace Control for Precise Text Layout
Learn how to precisely control whitespace (spaces, tabs, newlines) in your CSS layouts using the `white-space` property. This tutorial explains different `white-space` values (normal, nowrap, pre, pre-line, pre-wrap), demonstrating how to manage text wrapping and multiple whitespace characters for consistent and accurate text rendering.
Controlling Whitespace with CSS `white-space`
Understanding `white-space`
The CSS `white-space` property controls how whitespace characters (spaces, tabs, and newlines) are handled within an element. It affects how text wraps and how multiple whitespace characters are displayed. This property is essential for fine-tuning text layout and ensuring consistent rendering across different browsers.
`white-space` Property Values
The `white-space` property accepts these values:
Value | Description |
---|---|
normal |
(Default) Multiple whitespace characters collapse into a single space. Text wraps to the next line when necessary. |
nowrap |
Multiple whitespace characters collapse into a single space. Text never wraps to the next line unless a line break (<br> ) is explicitly used. |
pre |
All whitespace characters are preserved. Text only wraps at explicit line breaks. This behavior is similar to the HTML <pre> tag. |
pre-line |
Multiple whitespace characters collapse into a single space. Text wraps at line breaks. |
pre-wrap |
Whitespace is preserved, but text wraps at line breaks and when necessary. |
initial |
Sets the property to its default value (normal ). |
inherit |
Inherits the value from its parent element. |
Example: `white-space` Values
This example demonstrates the effect of different `white-space` values. You'll need to create corresponding HTML elements (e.g., paragraphs with multiple spaces) to see these effects. The `white-space` property is applied to the containing element.
Illustrative CSS
p.normal { white-space: normal; }
p.nowrap { white-space: nowrap; }
p.pre { white-space: pre; }
p.pre-line { white-space: pre-line; }
p.pre-wrap { white-space: pre-wrap; }