CSS White Space
The CSS white-space property is used to control how white spaces are handled within an element. This property plays a crucial role in controlling how text and other content are displayed, especially with regards to wrapping, line breaks, and spacing between elements.
Key Points on CSS White Space:
- The
white-space
property specifies how white spaces inside an element are handled. - Different values of the
white-space
property can prevent text from wrapping, preserve line breaks, or collapse extra spaces. - The property can be applied to block-level and inline elements.
- By default, browsers collapse multiple spaces into a single space, but
white-space: pre;
can prevent this. - Useful for handling long text, such as in code blocks or poetry, where precise control of spacing is necessary.
Syntax for CSS White-Space Property:
Syntax Example
/* White-space syntax */
white-space: normal|nowrap|pre|pre-wrap|pre-line|break-spaces;
Examples of CSS White-Space Property:
The following examples demonstrate how the white-space
property works:
Code Example: White-Space Normal
div {
white-space: normal;
}
Output
This div has normal white space, meaning text will wrap normally.
Code Example: White-Space Pre
div {
white-space: pre;
}
Output
This div has pre white space, which preserves line breaks and spaces.
Code Example: White-Space Pre-Wrap
div {
white-space: pre-wrap;
}
Output
This div has pre-wrap white space, which preserves line breaks and wraps long text.
Common White-Space Values:
- normal: Collapses white space and allows text to wrap.
- nowrap: Collapses white space but prevents text from wrapping (single line).
- pre: Preserves both white space and line breaks (similar to
<pre>
tag behavior). - pre-wrap: Preserves white space and wraps the text if necessary.
- pre-line: Collapses white space, but preserves line breaks.
- break-spaces: Preserves white space and allows line breaks, treating spaces like line breaks.
The white-space
property can be especially useful when formatting code snippets, text areas, or any content where whitespace and line breaks need to be controlled explicitly. Choosing the right value can significantly affect how content is presented.