HTML
Web Development
Coding
Text Wrapping
Pre Tag

How do I wrap text in a pre tag?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To wrap text inside an HTML <pre> tag, apply white-space: pre-wrap in CSS. This preserves the whitespace and line breaks that make <pre> useful while allowing the browser to wrap long lines at the container boundary instead of forcing horizontal scrolling.

css
pre {
  white-space: pre-wrap;
}

That is the core answer. The rest of this article covers why <pre> does not wrap by default, how to handle extremely long unbroken strings, when wrapping is the wrong choice, and how to build a production-quality code block component that works across screen sizes.

Why <pre> Does Not Wrap by Default

The browser's default stylesheet applies white-space: pre to <pre> elements. This mode:

  • Preserves all spaces and tabs exactly as written
  • Preserves explicit line breaks (newlines in the source)
  • Disables automatic line wrapping entirely

This behavior is intentional. <pre> stands for "preformatted text," and the whole point is that the content should render exactly as authored. Code listings, ASCII art, and fixed-width tables all depend on this.

The problem appears when a single line is wider than the container. Without wrapping, the content overflows and creates a horizontal scrollbar, or worse, extends beyond the visible area with no scrollbar at all.

The white-space Property Values

Understanding the full set of white-space values clarifies why pre-wrap is the right choice:

ValuePreserves SpacesPreserves NewlinesAuto-Wraps
normalNo (collapses)No (collapses)Yes
nowrapNo (collapses)No (collapses)No
preYesYesNo
pre-wrapYesYesYes
pre-lineNo (collapses)YesYes
break-spacesYes (even trailing)YesYes

pre-wrap is the only value that preserves both spaces and newlines while also enabling automatic line wrapping. It keeps the formatting behavior of <pre> and adds the wrapping behavior of normal text.

Basic Implementation

html
1<pre class="wrapped">
2This is a very long line that would normally overflow the container and cause horizontal scrolling, but with pre-wrap it breaks at the container edge while still preserving all     spaces     and
3explicit line breaks.
4</pre>
css
.wrapped {
  white-space: pre-wrap;
}

The multiple spaces between "all," "spaces," and "and" are preserved. The explicit newline before "explicit line breaks" is also preserved. But the long first line wraps at the container width instead of overflowing.

Handling Long Unbroken Strings

pre-wrap wraps at word boundaries (spaces, hyphens). If the content contains a very long token with no break opportunities (a URL, a base64 string, a long variable name), the browser may still overflow the container.

Add overflow-wrap to allow breaking within long words:

css
1.wrapped {
2  white-space: pre-wrap;
3  overflow-wrap: break-word;
4}

For even more aggressive breaking:

css
1.wrapped {
2  white-space: pre-wrap;
3  overflow-wrap: anywhere;
4}

The difference between break-word and anywhere is subtle: anywhere allows the browser to consider mid-word breaks when calculating minimum content width, which affects layout in flex and grid containers. For most <pre> use cases, break-word is sufficient.

Legacy Compatibility

The word-wrap property is the old name for overflow-wrap. Both work in all modern browsers, but overflow-wrap is the standard name:

css
1/* For maximum compatibility */
2.wrapped {
3  white-space: pre-wrap;
4  word-wrap: break-word;      /* legacy */
5  overflow-wrap: break-word;  /* standard */
6}

Production Code Block Styling

A real-world code block needs more than just wrapping. Here is a complete, production-ready style:

css
1pre.code-block {
2  white-space: pre-wrap;
3  overflow-wrap: break-word;
4  padding: 16px;
5  margin: 16px 0;
6  background-color: #1e1e1e;
7  color: #d4d4d4;
8  border-radius: 6px;
9  font-family: 'Fira Code', 'Consolas', 'Monaco', monospace;
10  font-size: 14px;
11  line-height: 1.6;
12  tab-size: 4;
13  -moz-tab-size: 4;
14}
html
1<pre class="code-block">
2SELECT u.id, u.name, u.email, o.order_id, o.total_amount, o.created_at
3FROM users u
4INNER JOIN orders o ON u.id = o.user_id
5WHERE o.created_at >= '2024-01-01' AND o.status = 'completed'
6ORDER BY o.total_amount DESC
7LIMIT 100;
8</pre>

The tab-size property controls how tab characters render. The default is 8 spaces, which is too wide for most code. Setting it to 4 (or 2) keeps indentation reasonable.

When Not to Wrap: Use Horizontal Scrolling Instead

Wrapping is not always the right choice. Some content is meaningfully laid out in columns, and wrapping destroys readability:

  • ASCII art and diagrams
  • Fixed-width data tables
  • Code where indentation alignment carries meaning (YAML, Python)
  • Diff output

For these cases, use overflow-x: auto instead:

css
1pre.scroll-block {
2  white-space: pre;
3  overflow-x: auto;
4  padding: 16px;
5  background-color: #f5f5f5;
6  border: 1px solid #e0e0e0;
7  border-radius: 6px;
8  font-family: monospace;
9}

This preserves the exact layout and adds a horizontal scrollbar only when content overflows.

Responsive Strategy: Wrap on Mobile, Scroll on Desktop

You can use different strategies at different viewport widths:

css
1pre.responsive-block {
2  white-space: pre;
3  overflow-x: auto;
4  padding: 16px;
5  background-color: #f5f5f5;
6  font-family: monospace;
7}
8
9@media (max-width: 768px) {
10  pre.responsive-block {
11    white-space: pre-wrap;
12    overflow-wrap: break-word;
13    overflow-x: visible;
14  }
15}

On desktop, users get a scrollbar to see the full line. On mobile, lines wrap to fit the screen. This is a practical compromise for documentation sites and blogs that need to work on all devices.

Using <pre> With <code> Elements

In semantic HTML, code blocks use <pre> wrapped around <code>:

html
1<pre><code class="language-python">
2def fibonacci(n):
3    if n <= 1:
4        return n
5    return fibonacci(n - 1) + fibonacci(n - 2)
6</code></pre>

When nesting these elements, apply the wrapping styles to <pre> and reset any conflicting styles on <code>:

css
1pre {
2  white-space: pre-wrap;
3  overflow-wrap: break-word;
4}
5
6pre code {
7  white-space: inherit;
8  word-break: normal;
9}

The inherit value ensures <code> does not override the wrapping behavior set on <pre>.

Comparison of Overflow Strategies

StrategyCSSPreserves LayoutWorks on MobileBest For
Wrappingwhite-space: pre-wrapPartially (line breaks change)YesProse, logs, stack traces
Horizontal scrolloverflow-x: autoFullyUsable but awkwardCode, tables, diagrams
Responsive hybridMedia query switchDesktop: full; Mobile: wrapYesDocumentation, blogs
Forced breakoverflow-wrap: anywhereNo (breaks mid-word)YesURLs, long tokens

Common Pitfalls

Using white-space: normal instead of pre-wrap is a frequent mistake. While normal enables wrapping, it also collapses multiple spaces into one and ignores explicit newlines, destroying the preformatted nature of the content.

Applying pre-wrap without overflow-wrap fails when content includes unbreakable strings like URLs or base64 data. The browser wraps at spaces but cannot break the long token, so it still overflows.

Forgetting to set tab-size leaves tabs rendering at the browser default of 8 spaces, which makes indented code look excessively wide.

Styling only the desktop view and ignoring mobile leads to <pre> blocks that overflow the viewport on phones, breaking the entire page layout. Always test <pre> elements at narrow widths.

Using word-break: break-all instead of overflow-wrap: break-word breaks words at arbitrary points even when there are natural break opportunities. This produces ugly results for normal text. Prefer overflow-wrap, which only breaks words as a last resort.

Setting overflow: hidden on <pre> silently clips content without any visual indication, making users unaware that text is missing. Use overflow-x: auto (scrollbar) or pre-wrap (wrapping), never hidden.

Summary

  • Apply white-space: pre-wrap to <pre> elements to enable wrapping while preserving whitespace and line breaks.
  • Add overflow-wrap: break-word to handle long unbroken strings that would otherwise overflow.
  • Use overflow-x: auto instead of wrapping when exact column alignment matters (code, tables, diagrams).
  • Consider a responsive approach: scroll on desktop, wrap on mobile.
  • Never use white-space: normal on <pre> because it collapses the whitespace that <pre> is designed to preserve.
  • Set tab-size: 4 to prevent tabs from rendering at the default width of 8 spaces.

Course illustration
Course illustration

All Rights Reserved.