Usage of white-space property in CSS

The CSS white-space property controls how whitespace characters (spaces, tabs, line breaks) are handled within an element. It determines whether text wraps, how spaces are collapsed, and whether line breaks are preserved.

Syntax

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

White-space Values

Value Spaces Collapsed? Line Breaks Honored? Text Wraps?
normal Yes No Yes
nowrap Yes No No
pre No Yes No
pre-wrap No Yes Yes
pre-line Yes Yes Yes

Example: Using white-space: pre

<html>
   <head>
      <style>
         .pre-example {
            white-space: pre;
            font-family: monospace;
            background-color: #f5f5f5;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <p class="pre-example">This text has    multiple spaces
and line breaks that are preserved
      just like the HTML pre tag.</p>
   </body>
</html>

Example: Comparing Different Values

<html>
   <head>
      <style>
         .container {
            width: 200px;
            border: 1px solid #ccc;
            margin: 10px 0;
            padding: 5px;
         }
         .normal { white-space: normal; }
         .nowrap { white-space: nowrap; }
         .pre-wrap { white-space: pre-wrap; }
      </style>
   </head>
   <body>
      <div class="container normal">
         <strong>normal:</strong> This is a long text with    extra spaces
that will wrap normally.
      </div>
      
      <div class="container nowrap">
         <strong>nowrap:</strong> This text will not wrap even if it's very long.
      </div>
      
      <div class="container pre-wrap">
         <strong>pre-wrap:</strong> This preserves    spaces
and line breaks
         while still wrapping.
      </div>
   </body>
</html>

Common Use Cases

Code Display: Use pre or pre-wrap to preserve formatting in code blocks.

Prevent Wrapping: Use nowrap for navigation menus or buttons that should stay on one line.

Poetry/Addresses: Use pre-line to preserve line breaks while allowing normal space handling.

Conclusion

The white-space property provides fine control over text formatting. Use pre for code, nowrap to prevent wrapping, and pre-wrap when you need both preservation and wrapping.

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

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements