Control the flow and formatting of text with CSS

The white-space property is used to control the flow and formatting of text in CSS. It determines how whitespace characters (spaces, tabs, line breaks) inside an element are handled.

Syntax

white-space: normal | nowrap | pre | pre-wrap | pre-line;

White-space Values

Value Line Breaks Spaces/Tabs Text Wrapping
normal Ignored Collapsed Yes
nowrap Ignored Collapsed No
pre Preserved Preserved No
pre-wrap Preserved Preserved Yes
pre-line Preserved Collapsed Yes

Example: Using white-space: pre

The pre value preserves all whitespace exactly as written in the HTML:

<html>
    <head>
        <style>
            .pre-text {
                white-space: pre;
                border: 1px solid #ccc;
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <p class="pre-text">This text has     multiple spaces
and a line break that will be preserved
        exactly as written.</p>
    </body>
</html>

Example: Comparing Different Values

<html>
    <head>
        <style>
            .example {
                border: 1px solid #ddd;
                margin: 10px 0;
                padding: 10px;
                width: 200px;
            }
            .normal { white-space: normal; }
            .nowrap { white-space: nowrap; }
            .pre-wrap { white-space: pre-wrap; }
        </style>
    </head>
    <body>
        <div class="example normal">
            <strong>Normal:</strong> This   text   has
            multiple spaces and will wrap normally.
        </div>
        
        <div class="example nowrap">
            <strong>Nowrap:</strong> This text will not wrap and may overflow.
        </div>
        
        <div class="example pre-wrap">
            <strong>Pre-wrap:</strong> This   preserves   spaces
            but still wraps text when needed.
        </div>
    </body>
</html>

Common Use Cases

  • Code Display: Use pre or pre-wrap for showing formatted code
  • Poetry/Addresses: Use pre-line to preserve line breaks but collapse spaces
  • Navigation Menus: Use nowrap to prevent menu items from breaking
  • Normal Text: Use normal (default) for regular paragraph text

Conclusion

The white-space property gives you precise control over text formatting and spacing. Choose the appropriate value based on whether you need to preserve spaces, line breaks, and text wrapping behavior.

Updated on: 2026-03-15T23:18:59+05:30

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements