Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set the whitespace between text in CSS?
The CSS white-space property controls how whitespace characters (spaces, tabs, line breaks) are handled within text elements. This property is essential for controlling text formatting and layout.
Syntax
white-space: value;
White-space Property Values
| Value | Spaces/Tabs | Line Breaks | Text Wrapping |
|---|---|---|---|
normal |
Collapsed | Ignored | Yes |
pre |
Preserved | Preserved | No |
nowrap |
Collapsed | Ignored | No |
pre-wrap |
Preserved | Preserved | Yes |
pre-line |
Collapsed | Preserved | Yes |
Example: Using white-space: pre
The pre value preserves all whitespace and line breaks, similar to the HTML <pre> tag:
<html>
<head>
<title>White-space Example</title>
</head>
<body>
<p style="white-space: pre;">
This text has multiple spaces
and a line break that will be preserved
exactly as written in the HTML.
</p>
</body>
</html>
Example: Comparing Different Values
<html>
<head>
<style>
.normal { white-space: normal; }
.pre { white-space: pre; }
.nowrap { white-space: nowrap; }
.pre-wrap { white-space: pre-wrap; }
div {
border: 1px solid #ccc;
margin: 10px;
padding: 10px;
width: 200px;
}
</style>
</head>
<body>
<div class="normal">
Normal: Multiple spaces
and line breaks are collapsed.
</div>
<div class="pre">
Pre: Multiple spaces
and line breaks are preserved.
</div>
<div class="nowrap">
Nowrap: This very long text will not wrap to the next line even if the container is narrow.
</div>
<div class="pre-wrap">
Pre-wrap: Preserves spaces
and breaks, but allows wrapping.
</div>
</body>
</html>
Common Use Cases
Code Display: Use white-space: pre or pre-wrap for displaying code snippets where indentation matters.
Preventing Text Wrap: Use white-space: nowrap for navigation menus or buttons where text should stay on one line.
Poetry or Formatted Text: Use white-space: pre-line to preserve line breaks while allowing normal space handling.
Conclusion
The white-space property provides precise control over text formatting. Choose pre for exact spacing preservation, nowrap to prevent wrapping, or normal for standard text flow.
