White-Space Handling in CSS
What You Learn From This Page
- How browsers collapse or preserve spaces, tabs, and source line breaks.
- How normal, nowrap, pre, pre-wrap, pre-line, and break-spaces differ.
- How white-space interacts with wrapping, overflow, Flexbox, and Grid sizing.
- How to render code, logs, addresses, notes, chat messages, and API text safely.
- How to avoid layout spaces, inaccessible no-wrap interfaces, and hidden content.
- How to test and debug whitespace across languages, viewports, and exports.
Introduction
Whitespace looks simple in source code, yet it participates in several stages of browser text layout. HTML can contain ordinary spaces, tabs, and line-feed characters. CSS then decides whether sequences collapse, whether source line breaks become visible breaks, and whether text may wrap at normal opportunities. Those decisions affect paragraphs, navigation, buttons, code samples, logs, user comments, addresses, tables, and almost every responsive component.
The white-space property is the primary control. Its common values combine collapsing and wrapping behavior into recognizable presets. Choosing the right value is not merely cosmetic. A poor choice can destroy user-entered formatting, expose source indentation, create horizontal overflow, hide critical instructions, or make translated labels unusable on small screens.
What Is White Space?
In everyday HTML and CSS discussion, whitespace commonly refers to space characters, tab characters, and segment breaks such as source newlines. These characters are part of the document data even when the browser renders several of them as one visible gap. CSS whitespace processing changes presentation; it does not rewrite the underlying text.
<p>
Hello CSS
World
</p>
With normal processing, the indentation, repeated spaces, and source newline collapse into ordinary flowing text. The result appears approximately as "Hello CSS World" and can wrap according to the available inline size.
The Two Main Questions
The white-space property answers two central questions. First, should sequences of white-space characters collapse or remain preserved? Second, may the browser wrap the line at unforced soft wrap opportunities? Source line breaks add a third practical concern because some values preserve them as forced breaks while others transform them during collapsing.
Thinking in these dimensions is more reliable than memorizing screenshots. Once you know whether spaces collapse, whether source breaks survive, and whether soft wrapping is allowed, the major values become predictable.
white-space Syntax and Inheritance
The property is declared on text-containing elements and is inherited. A value applied to a component can therefore affect descendant text unless a more specific element changes it. That is useful for a log viewer but risky on a large application shell.
.content {
white-space: normal;
}
The initial value is normal. The stable classic keywords are normal, nowrap, pre, pre-wrap, pre-line, and break-spaces.
white-space: normal
normal is the standard behavior for paragraphs and general interface text. Sequences of collapsible whitespace become a single rendered separation or, in some contexts, no visible character. Source segment breaks collapse, and lines may wrap at allowed soft wrap opportunities to reduce inline overflow.
p {
white-space: normal;
}
This behavior lets authors indent HTML for readability without exposing that indentation in the page. It also lets prose adapt naturally as containers narrow, text grows, or translations become longer.
How normal Collapses Source Formatting
Consider a paragraph split across several source lines with extra spaces around inline elements. Under normal processing, the browser combines collapsible sequences according to the formatting context. The source layout helps developers read markup, while the rendered paragraph follows typographic line-breaking rules.
Do not assume every newline becomes a visible space in every language. Segment-break transformation can depend on context and writing system. Use actual content and correct language metadata rather than treating source newlines as a universal text separator.
When to Use normal
Use normal for articles, descriptions, help text, form guidance, validation messages, notifications, and most labels that can wrap. It provides the most resilient baseline because the content can reflow when available space changes.
If a design fails under normal wrapping, investigate the component width, word-breaking behavior, or layout before disabling wrapping. A one-line restriction should represent a genuine product requirement, not a patch for an inflexible container.
white-space: nowrap
nowrap collapses whitespace much like normal but suppresses unforced soft wrapping. The content remains on one line unless a forced break mechanism applies. Long content can therefore exceed the element's inline size and influence intrinsic sizing.
.status-badge {
white-space: nowrap;
}
No-wrap can suit short badges, compact metadata, or controlled labels. It becomes dangerous when content is dynamic, translated, or essential to completing a task.
nowrap and Single-Line Ellipsis
The most familiar no-wrap pattern combines constrained space, clipped overflow, and a text-overflow marker. No-wrap keeps the text on one line so the excess reaches the inline clipping edge.
.title {
min-inline-size: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Ellipsis does not make no-wrap safe for every label. If the hidden ending carries meaning, allow wrapping or provide dependable access to the complete value.
Good and Poor nowrap Candidates
A short amount with its unit, a compact date, or a small status chip may need to stay together. An error message, legal condition, security warning, form instruction, or descriptive button label usually should wrap rather than overflow or disappear.
Review content type before adding no-wrap. The question is not whether a single line looks cleaner in a mockup, but whether preserving one line is more important than preserving readable information under real conditions.
white-space: pre
pre preserves spaces, tabs, and source segment breaks. Lines break at preserved forced breaks but do not normally wrap at soft opportunities. This behavior is appropriate when horizontal positioning and line structure are meaningful.
.raw-output {
white-space: pre;
overflow-x: auto;
}
A long preserved line can overflow. A scrollable code or data region often handles that intentionally, while ordinary prose generally should not use pre.
The HTML pre Element
User-agent styles commonly give the HTML <pre> element whitespace-preserving behavior and a monospace font. The semantic element identifies preformatted text, while CSS controls its final wrapping and overflow presentation.
<pre><code>function ready() {
return true;
}</code></pre>
Use semantic preformatted markup for code, terminal output, and text whose arrangement is part of its meaning. Do not use it merely to obtain a monospace font.
Code Blocks with Horizontal Scrolling
Preserving code exactly and allowing horizontal scrolling avoids inserting visual wraps that can be mistaken for actual source lines. A maximum inline size and scoped scrolling keep long lines from widening the entire page.
pre {
max-inline-size: 100%;
overflow-x: auto;
white-space: pre;
}
Ensure the scroll region is keyboard accessible when necessary and remains usable with zoom. Very long unbroken output may also need copy controls or a dedicated expanded view.
white-space: pre-wrap
pre-wrap preserves spaces, tabs, and source line breaks while allowing soft wrapping. It is one of the most useful values for user-entered notes, comments, chat messages, and logs that should retain formatting without forcing horizontal page overflow.
.user-message {
white-space: pre-wrap;
}
The browser preserves intentional blank lines and repeated spaces, then wraps long content when the line reaches its available size. Extremely long tokens may still need an overflow-wrap rule.
User-Entered Notes
Text entered through a textarea often contains deliberate line breaks. Rendering the saved value under normal whitespace collapses those breaks and can turn a structured note into one paragraph. Pre-wrap retains the author's visible structure while remaining responsive.
.saved-note {
white-space: pre-wrap;
overflow-wrap: anywhere;
line-height: 1.55;
}
Escape untrusted text before rendering it into HTML. Whitespace preservation is a presentation choice and does not replace output encoding or sanitization.
Chat and Messaging Content
Chat messages commonly contain short paragraphs, copied links, blank lines, and informal spacing. Pre-wrap preserves those choices while allowing bubbles to shrink on narrow screens. Adding overflow-wrap: anywhere protects the layout from long URLs and machine-generated strings.
Do not preserve formatting by replacing every newline with a <br> through unsafe string operations. Render trusted text safely and let CSS express its whitespace policy.
white-space: pre-line
pre-line collapses sequences of spaces but preserves source segment breaks as forced line breaks. It also allows normal soft wrapping. This is useful when line grouping matters but horizontal indentation and repeated spaces do not.
.address {
white-space: pre-line;
}
An address, multi-line label, or simple API message can retain its lines without reproducing accidental spacing from data entry or source indentation.
pre-wrap Versus pre-line
Both values preserve source line breaks and allow wrapping. The difference is how they treat spaces and tabs. Pre-wrap preserves them, while pre-line collapses them. That distinction determines whether user indentation, aligned columns, or repeated spaces remain visible.
Choose pre-wrap when horizontal whitespace is meaningful. Choose pre-line when only the line divisions matter. If neither is meaningful, use normal.
white-space: break-spaces
break-spaces strongly preserves whitespace and allows wrapping. Unlike pre-wrap, every sequence of preserved whitespace continues to occupy space, including at line ends, and a soft wrap opportunity exists after each preserved space or separator.
.spacing-demo {
white-space: break-spaces;
}
This value is specialized. It is useful for editors, demonstrations, or text where exact spaces must remain measurable while the content can still wrap.
break-spaces Versus pre-wrap
Both preserve spaces, tabs, and source line breaks, and both permit wrapping. Pre-wrap can let sequences at line ends hang and commonly wraps after a preserved run. Break-spaces treats preserved spaces more like visible characters and permits wrapping after each one.
The difference becomes clear with trailing spaces, multiple adjacent spaces near a boundary, and intrinsic sizing. Test the exact content instead of assuming the two values are interchangeable.
Comparison of Major Values
| Value | Spaces and tabs | Source line breaks | Soft wrapping |
|---|---|---|---|
normal | Collapse | Collapse | Allowed |
nowrap | Collapse | Collapse | Suppressed |
pre | Preserve | Preserve | Suppressed |
pre-wrap | Preserve | Preserve | Allowed |
pre-line | Collapse | Preserve | Allowed |
break-spaces | Preserve strongly | Preserve | Allowed after spaces |
A Practical Memory Model
Normal means ordinary flowing web text. Nowrap means collapse like normal but do not take soft wraps. Pre means preserve source formatting and do not soft-wrap. Pre-wrap means preserve and wrap. Pre-line means preserve line breaks but collapse repeated spaces. Break-spaces means preserve whitespace with stronger wrapping behavior around each space.
This model is accurate enough for everyday work while leaving room for deeper details such as hanging end-of-line spaces, language-specific segment transformation, and intrinsic sizing.
Tabs and tab-size
Tabs matter only when they survive whitespace processing. The tab-size property controls the width used to render tab characters in contexts that preserve them. Code style conventions often prefer two or four columns rather than the browser's default.
pre {
white-space: pre;
tab-size: 2;
}
Tab rendering is presentation; it does not convert tabs into spaces in the underlying text. Copying the content can still preserve the original characters.
White Space Is Not Layout Spacing
Typing repeated spaces to align labels and values creates fragile layout. Collapsing may remove them, fonts use different glyph widths, translations change text length, and assistive technology does not receive a meaningful column structure.
.detail-row {
display: grid;
grid-template-columns: 8rem minmax(0, 1fr);
gap: 1rem;
}
Use Grid, Flexbox, gap, margin, padding, and semantic tables for layout. Preserve spaces only when they are genuinely part of the content.
Non-Breaking Spaces
A non-breaking space can keep a small semantic unit together, such as a number and its unit or an abbreviated title and name. In HTML it can be written as , though Unicode input or generated text may contain the character directly.
<span>10 GB</span>
Do not repeat non-breaking spaces to create indentation or navigation gaps. They suppress valid break opportunities and can force mobile overflow.
white-space Versus overflow-wrap
White-space controls collapsing and whether ordinary soft wrapping is permitted. overflow-wrap adds emergency opportunities when an otherwise unbreakable sequence would overflow. The properties solve related but distinct problems.
.api-message {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
This combination preserves user or server-provided formatting while allowing a long URL or identifier to break before it widens the interface.
white-space Versus word-break
word-break controls line-breaking opportunities between letters and across writing systems. break-all can split Latin words between arbitrary characters, which protects width but may reduce readability. It does not decide whether repeated spaces collapse.
.machine-code {
white-space: normal;
word-break: break-all;
}
Use language-appropriate wrapping for human text. Reserve aggressive breaking for machine values where preserving the container is more important than preserving word shape.
white-space Versus text-overflow
text-overflow represents clipped inline content with clipping or an ellipsis. It does not control whitespace collapsing or create a single line. That is why single-line truncation commonly includes white-space: nowrap.
If the content should remain complete, do not reach for ellipsis automatically. Normal wrapping or pre-wrap may solve the problem without hiding information.
White Space and Flexbox
A no-wrap flex item can contribute a large intrinsic minimum size and force its row wider than expected. If the item is intended to shrink and truncate, its flexible wrapper may need a zero logical minimum.
.user-row {
display: flex;
gap: 0.75rem;
}
.user-row__content {
flex: 1;
min-inline-size: 0;
}
Apply no-wrap and ellipsis to the nested title, not to the whole row. This avoids clipping buttons, badges, and focus indicators.
White Space and Grid
Grid tracks can also preserve intrinsic content minimums. A track containing no-wrap text may expand the grid instead of allowing the text box to become narrow. A zero-minimum fractional track explicitly permits shrinking.
.record-row {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
}
Use this sizing pattern only where the middle track has an intentional wrapping, clipping, or truncation strategy.
White Space in Tables
Tables calculate column sizes from content. A long no-wrap status or identifier can make the entire table wider than its container. Wrapping may be preferable; otherwise, constrain an inner wrapper, provide horizontal scrolling, or move details into an expandable row.
Do not hide important table data simply to preserve a desktop column layout on mobile. Responsive tables need a deliberate information hierarchy.
White Space in Buttons
Keeping a short button label on one line can protect a compact toolbar, but translated labels and increased text size can exceed the button width. Fixed heights and no-wrap are especially risky together because the label cannot reflow vertically.
.action-button {
min-block-size: 2.75rem;
padding-inline: 1rem;
white-space: normal;
}
Allow wrapping for descriptive actions unless the component can grow horizontally and every supported label is known to fit.
Rendering Textarea Content
A textarea preserves line breaks while the user edits. When its saved value is displayed in a regular element, normal whitespace may collapse those breaks. Use pre-wrap when both line breaks and repeated spaces matter, or pre-line when only line structure matters.
Maintain a clear separation between storage, safe HTML encoding, and CSS rendering. Do not store inserted <br> tags merely to reproduce line breaks.
Rendering API Data
An API may return a plain-text message with newline characters. The correct presentation depends on the contract. A legal notice may require exact paragraphs, an address may need pre-line, and a stack trace may need pre with horizontal scrolling.
.server-message {
white-space: pre-line;
}
.server-log {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
Choose by meaning rather than by data source. Not every string containing a newline should preserve indentation.
Log Viewer Patterns
Logs can contain timestamps, aligned columns, stack traces, tabs, long URLs, and very long unbroken identifiers. A desktop diagnostics tool may preserve each line and scroll horizontally, while an embedded support panel may wrap to fit.
.log-viewer {
font-family: monospace;
overflow: auto;
white-space: pre;
}
.log-viewer--wrap {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
Offer a user-controlled wrap toggle when both exact line structure and narrow-screen reading matter.
Addresses and Structured Plain Text
Addresses, signatures, and simple multi-line descriptions often need preserved line breaks but not preserved horizontal gaps. Pre-line offers a clean mapping from newline-separated data to responsive rendered lines.
.postal-address {
white-space: pre-line;
}
Use semantic address markup where appropriate. The whitespace rule handles presentation, not the document meaning.
Source Indentation Can Become Visible
Preserving whitespace in an element also preserves indentation written around its text nodes. A nicely indented HTML template can therefore create unintended leading spaces and blank lines when switched from normal to pre-wrap or pre.
Inspect the actual DOM text, not only the visible source lines. Place preserved text deliberately, or provide it as data without surrounding template indentation.
Trailing Spaces and Intrinsic Sizing
Trailing preserved spaces can hang, wrap, or contribute to intrinsic size differently depending on the value. This detail explains why pre-wrap and break-spaces can behave differently even when ordinary examples look identical.
Editors, diff viewers, and whitespace demonstrations should test leading, internal, and trailing sequences at narrow widths. General user interfaces should avoid relying on invisible trailing spaces for meaningful alignment.
Multilingual Content
Writing systems do not all use spaces and line breaks like English. Segment-break transformation and soft wrapping follow language-sensitive rules. A globally applied no-wrap or break-all policy can damage readability in scripts with different conventions.
Set accurate lang and dir attributes, use fonts supporting the required scripts, and test real translations. White-space behavior is part of internationalized typography, not merely an English formatting detail.
Accessibility and Reflow
Users may zoom, enlarge text, increase text spacing, or use a narrow viewport. No-wrap content consumes more inline space under all of those changes. It can overlap controls, force two-dimensional scrolling, or become clipped before its meaning is complete.
Prefer wrapping for critical and instructional content. Use natural height or minimum dimensions rather than fixed heights, and verify that preserved blank lines do not create confusing navigation or enormous empty regions.
Print, PDF, and Word Export
A scrollable preformatted region may work on screen but lose content when printed. Print styles can choose wrapping for logs and code where preserving every character matters more than preserving physical lines. Conversely, legal or tabular material may require landscape layout and exact formatting.
@media print {
pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
}
Inspect actual exports because font substitution and page widths change line breaking. Ensure no essential content remains outside the printable area.
Modern Longhand Concepts
CSS Text Level 4 describes white-space through more granular concepts, including white-space-collapse and text-wrap-mode. These separate whether whitespace collapses from whether soft wrapping is enabled. Other evolving controls address trimming and wrap style.
The classic keywords remain the most portable way to express common combinations. Check current browser support before replacing them with newer longhands in production code.
Whitespace in Templates and Dynamic Rendering
Component templates frequently contain indentation and newlines that exist only to make source code readable. Under normal processing, those characters usually collapse harmlessly. If a component later switches to pre or pre-wrap, however, the formatting around interpolation boundaries can become visible as leading spaces, blank lines, or unexpected gaps between inline fragments.
<div class="message">
{{ userMessage }}
</div>
When the message container preserves whitespace, the newline and indentation surrounding the interpolated value may become part of the rendering. Framework behavior differs according to how templates compile text nodes, so inspect the generated DOM and the actual string rather than assuming the source indentation is removed.
Data transformations can introduce another layer of inconsistency. Windows text commonly uses carriage-return and line-feed pairs, Unix text uses line feeds, and external systems may send literal escape sequences instead of real newline characters. HTML parsing normalizes actual newlines for the DOM, but a string containing the two visible characters backslash and n is not a line break. Normalize data at a clear boundary when the application contract requires it, then choose CSS according to the resulting text semantics.
Generated Content and Inline Element Boundaries
Whitespace around inline elements is still part of the surrounding inline formatting context. A source newline between two inline elements can collapse into a visible gap under normal processing, while removing every gap in minified markup can make words or controls run together. Pseudo-element content can also add visible characters but should not carry essential wording.
<span>Hello</span>
<span>World</span>
If the intended result is two separate words, provide a semantic separator in the content or use layout gap when the spans are independent interface items. Do not depend on a particular source indentation pattern that a formatter, minifier, or rendering framework may change.
Performance and Large Preserved Text
Whitespace selection rarely creates a meaningful performance problem for ordinary copy. Very large logs, generated reports, or editor buffers are different: preservation, wrapping, syntax highlighting, and continuous resizing can require substantial text layout work. Wrapping thousands of very long lines may be more expensive than showing a horizontally scrollable preformatted viewport.
Choose behavior from usability first, then measure realistic data. For extremely large output, virtualize visible records, paginate results, or move full diagnostics to a dedicated viewer. Do not hide performance problems by clipping information that users need.
Common Mistake: Expecting Spaces to Remain
Under normal processing, typing several spaces in HTML does not create a large visible gap. That behavior is intentional. If the spaces are content, choose a preserving value; if they are layout, use a layout property.
Common Mistake: Using Spaces for Columns
Manual spaces align only under one font, width, and data sample. A proportional font immediately exposes the weakness, and preserved whitespace can create overflow. Use a table for tabular data or Grid for label-value layouts.
Common Mistake: Repeating Non-Breaking Spaces
Multiple entities are not a replacement for margin, padding, or gap. They make wrapping unpredictable and pollute copied text. Reserve non-breaking spaces for small semantic groups that should stay together.
Common Mistake: Global nowrap
A global no-wrap rule can break navigation, forms, cards, tables, dialogs, and mobile pages. It also makes localization and user text settings far more fragile. Scope it to small components with a documented single-line requirement.
Common Mistake: pre on Responsive Prose
Pre preserves every space and suppresses soft wrapping, so a single long source line can widen the page. If line breaks and spaces matter but wrapping is acceptable, pre-wrap is usually a better fit.
Common Mistake: Confusing pre-wrap and pre-line
Both preserve source line breaks and permit wrapping. Pre-wrap also preserves repeated spaces and tabs; pre-line collapses them. Select based on whether horizontal whitespace carries meaning.
Common Mistake: Fixed Heights
Preserved line breaks and user content can produce more lines than a design sample. A fixed-height message box may clip the ending, overlap following content, or require awkward internal scrolling. Prefer natural height or a minimum height with an explicit expansion strategy.
Testing Strategy
Test repeated spaces, tabs, leading and trailing spaces, blank lines, Windows and Unix line endings as they appear after DOM normalization, long words, long URLs, and empty content. Use primary and fallback fonts, every supported language, zoom, and user spacing overrides.
Exercise paragraphs, buttons, form errors, table cells, code blocks, logs, notes, chat messages, API output, Flexbox, Grid, print, PDF, and Word export. Verify both visual behavior and copied text.
Debugging White-Space Problems
Inspect the computed white-space value and its inherited source. Use DevTools to view text nodes, element boundaries, used widths, and overflow. Temporarily switch among normal, pre, and pre-wrap to identify whether the problem is collapsing, wrapping, or layout sizing.
Reveal whitespace in the source editor, check for tabs and non-breaking spaces, and compare scroll width with client width. In flex and grid layouts, inspect intrinsic minimums before blaming the white-space property itself.
Related Property Comparison
| Property | Primary responsibility |
|---|---|
white-space | Collapse or preserve whitespace and control soft wrapping |
overflow-wrap | Add emergency breaks for long content |
word-break | Control where words or script runs may break |
text-overflow | Represent clipped inline overflow |
overflow | Handle content outside a box |
tab-size | Control the rendered advance of preserved tabs |
Common Interview Questions
What does white-space control? It controls whether whitespace collapses, whether source line breaks remain, and whether soft wrapping is allowed.
What is the initial value? The initial value is normal.
What does nowrap do? It collapses whitespace like normal but suppresses unforced soft wrapping.
What is the difference between pre and pre-wrap? Both preserve whitespace and source breaks; pre suppresses soft wrapping while pre-wrap allows it.
What is the difference between pre-wrap and pre-line? Pre-wrap preserves repeated spaces; pre-line collapses spaces while preserving source breaks.
When is break-spaces useful? It is useful when preserved spaces, including spaces near line ends, must occupy space and provide wrapping opportunities.
Which value suits user notes? Pre-wrap commonly preserves entered formatting while allowing responsive wrapping.
Which value is used for one-line ellipsis? No-wrap is commonly combined with constrained width, clipped overflow, and text-overflow ellipsis.
Should spaces create layout? No. Use Grid, Flexbox, gap, margin, padding, or semantic tables.
Why can nowrap break Flexbox? The content can create a large intrinsic minimum; the intended flexible item may need min-inline-size: 0.
Practical Review Checklist
- Use normal for ordinary paragraphs and interface text.
- Use nowrap only for genuine single-line requirements.
- Use pre for exact formatting with an overflow strategy.
- Use pre-wrap for user content that must preserve spaces and lines.
- Use pre-line when line breaks matter but repeated spaces do not.
- Use break-spaces only when its stronger preservation is needed.
- Combine preserved content with overflow-wrap for long tokens where appropriate.
- Use layout properties instead of manual spaces or repeated non-breaking spaces.
- Test Flexbox and Grid intrinsic sizing with no-wrap content.
- Allow critical labels, errors, instructions, and warnings to wrap.
- Test translations, zoom, text spacing, narrow containers, and fallback fonts.
- Verify screen, print, PDF, and Word output separately.
Key Takeaway
CSS whitespace handling is a combination of collapsing, source-break preservation, and soft wrapping. Normal collapses and wraps; nowrap collapses without wrapping; pre preserves without soft wrapping; pre-wrap preserves and wraps; pre-line preserves lines while collapsing repeated spaces; and break-spaces provides stronger preservation with wrap opportunities after spaces.
Select the value from the content's meaning and the component's responsive needs. Preserve user formatting deliberately, allow important information to reflow, use code and log overflow strategies explicitly, and never rely on typed spaces for layout. A sound whitespace policy remains readable across dynamic data, languages, zoom, narrow containers, and document exports.