Question

How to Wrap Text in a pre Tag in HTML

htmlcss

Question

In HTML, the <pre> element is useful for displaying code blocks and debugging output because it preserves whitespace and line breaks. However, by default, long text often stays on a single line and can overflow horizontally. How can I make the text inside a <pre> tag wrap onto multiple lines while still keeping the useful formatting behavior of the element?

Short Answer

By the end of this page, you will understand why <pre> elements do not wrap text by default, how CSS can change that behavior, and which white-space settings are most useful when you want to preserve formatting but still allow long lines to wrap.

Concept

The main concept behind this question is the CSS white-space property and how it affects text inside an HTML <pre> element.

A <pre> tag is designed to preserve:

  • spaces
  • tabs
  • line breaks

That makes it ideal for:

  • code samples
  • log output
  • debugging text
  • formatted plain text

However, the default behavior of <pre> is roughly equivalent to:

pre {
  white-space: pre;
}

This means:

  • keep all whitespace exactly as written
  • do not wrap lines automatically
  • only break lines where actual line breaks exist in the source

That is why long text can stretch far past the edge of the container.

To make text wrap, you usually change the white-space behavior with CSS. The most common choice is:

pre {
  white-space: pre-wrap;
}

This tells the browser:

  • preserve spaces and line breaks
  • but also allow long lines to wrap when needed

This matters in real programming because readable output is important. If logs, code examples, or debug text force horizontal scrolling, they become harder to inspect and use. Good wrapping improves usability, especially on smaller screens.

Mental Model

Think of a normal text element like a paragraph written on flexible paper: when the line gets too long, it wraps to the next line.

Think of a default <pre> element like text written on a long rigid strip of paper: it keeps going in one direction exactly as typed.

Using white-space: pre-wrap; turns that rigid strip into flexible paper while still keeping the original spacing and line breaks.

So:

  • <p> = wraps, but does not preserve spacing exactly
  • <pre> = preserves spacing, but does not wrap by default
  • <pre style="white-space: pre-wrap;"> = preserves spacing and wraps when needed
Take Quiz

Syntax and Examples

The key CSS property is white-space.

Basic solution

<pre class="output">This is a very long line of debug output that would normally keep going forever on one line, but now it can wrap inside the box.</pre>
.output {
  white-space: pre-wrap;
}

This preserves:

  • spaces
  • indentation
  • line breaks

And it also allows long lines to wrap.

Example with visible styling

<pre class="code-block">
function greet(name) {
    console.log("Hello, " + name);
}

const message = "This is a very long string that should wrap inside the pre element instead of overflowing outside the container.";
</pre>
.code-block {
  white-space: pre-wrap;
  padding: 12px;
  border: 1px solid #ccc;
  background: #f7f7f7;
}

In this example:

  • indentation is preserved
  • blank lines stay intact
  • long lines can wrap inside the box

If very long words still overflow

Sometimes a single long word or URL still will not break nicely. In that case, add:

pre {
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

This helps with content like:

  • long URLs
  • unbroken error strings
  • generated tokens
  • minified output

Step by Step Execution

Consider this HTML and CSS:

<pre class="debug">User data: {"name":"Alex","message":"This is a very long debug message that should wrap inside the pre element instead of causing horizontal scrolling."}</pre>
.debug {
  white-space: pre-wrap;
  overflow-wrap: break-word;
  width: 300px;
  border: 1px solid #999;
  padding: 8px;
}

Here is what happens step by step:

  1. The browser reads the <pre> element.
  2. A <pre> normally preserves whitespace and avoids automatic wrapping.
  3. The CSS rule white-space: pre-wrap; changes that behavior.
  4. The browser still keeps existing spaces and line breaks.
  5. Because the element width is 300px, the browser checks whether the text fits on one line.
  6. When the line becomes too long, it wraps onto the next line.
  7. If a very long unbroken word appears, overflow-wrap: break-word; allows it to break instead of overflowing.

The result is formatted text that remains readable inside a fixed-width container.

Real World Use Cases

This pattern is useful in many practical situations.

Code snippets on documentation pages

Developers often show code inside <pre> blocks. On mobile screens, long lines can overflow badly. Wrapping makes examples easier to read.

Debugging panels in web apps

A temporary debug area might print JSON, logs, or request details. Wrapping prevents giant lines from breaking the layout.

Error output viewers

If an app shows stack traces, API responses, or validation messages in a <pre>, wrapping helps users inspect the content without constant horizontal scrolling.

Admin dashboards

Monitoring tools often show logs or generated text output. Wrapping makes those logs fit inside cards, panels, or sidebars.

Plain text previews

If users upload text files or generated reports, <pre> with wrapping can preserve formatting while still fitting the page.

Take Quiz

Real Codebase Usage

In real projects, developers usually combine <pre> wrapping with a few other CSS rules for usability.

Common pattern

pre {
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

This is a common default when a project wants readable preformatted text.

Responsive documentation

Teams building docs sites often use wrapping to avoid horizontal scrolling on phones, while still preserving indentation.

Log and JSON viewers

Developers may render server responses inside a <pre> block during debugging:

<pre id="api-response"></pre>
const responseBox = document.getElementById("api-response");
responseBox.textContent = JSON.stringify(data, null, 2);

Then CSS makes it readable:

#api-response {
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

Configuration and error displays

In admin or internal tools, <pre> is often used for:

  • configuration dumps
  • exception details
  • raw API output
  • copied terminal output

Wrapping is especially common when the text is informative rather than meant to match exact line length.

When teams intentionally do not wrap

For some code viewers, developers keep the default white-space: pre; because exact line structure matters and horizontal scrolling is acceptable. So the choice depends on the purpose of the content.

Common Mistakes

Beginners often run into a few issues when trying to wrap text in a <pre> element.

Mistake 1: Expecting <pre> to wrap automatically

Broken expectation:

<pre>This is a very long line that keeps going and going and going and does not wrap by default.</pre>

Why it happens:

  • <pre> preserves formatting
  • it does not auto-wrap long lines by default

Fix:

pre {
  white-space: pre-wrap;
}

Mistake 2: Using word-wrap alone without changing white-space

pre {
  word-wrap: break-word;
}

This may not solve the main issue because the element is still using preformatted no-wrap behavior.

Better:

pre {
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

Mistake 3: Replacing <pre> with <div> and losing formatting

Broken approach:

<div class="output">
    indented text
    second line
</div>

A normal <div> collapses whitespace by default, so spacing and line breaks may not behave as expected.

Fix:

  • keep <pre> if preserving formatting matters
  • or apply suitable white-space rules to another element

Mistake 4: Confusing pre-wrap with pre-line

pre {
  white-space: pre-line;
}

pre-line preserves line breaks, but it collapses sequences of spaces. That means indentation may be lost.

If you want to preserve indentation, use:

pre {
  white-space: pre-wrap;
}

Mistake 5: Forgetting very long strings

Even with wrapping enabled, an unbroken string like a token or URL may still overflow.

Fix:

pre {
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

Comparisons

Here is how the most relevant white-space values compare.

ValuePreserves spacesPreserves line breaksWraps long lines
normalNoNoYes
preYesYesNo
pre-wrapYesYesYes
pre-lineNoYesYes

Which one should you use?

  • Use normal for regular paragraphs.
  • Use pre when exact original formatting matters and horizontal scrolling is acceptable.
  • Use pre-wrap when you want formatting and wrapping.
  • Use pre-line when line breaks matter but extra spacing does not.

<pre> vs normal elements

Element/StyleBest forMain limitation
<pre> defaultExact preformatted textLong lines do not wrap
<pre> + white-space: pre-wrapReadable formatted textSome code samples may wrap awkwardly
<div> or <p> defaultNormal text contentDoes not preserve indentation or source spacing
Take Quiz

Cheat Sheet

/* Default pre behavior */
pre {
  white-space: pre;
}

/* Most useful wrapping version */
pre {
  white-space: pre-wrap;
}

/* Better for long unbroken strings too */
pre {
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

Quick rules

  • <pre> preserves spaces and line breaks.
  • Default <pre> does not wrap long lines.
  • white-space: pre-wrap; preserves formatting and allows wrapping.
  • pre-line wraps, but collapses repeated spaces.
  • overflow-wrap: break-word; helps break long tokens or URLs.

Good default for readable output

pre {
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

Use cases

  • code examples
  • logs
  • stack traces
  • JSON output
  • debug panels

FAQ

How do I make text wrap inside a <pre> tag?

Use CSS like this:

pre {
  white-space: pre-wrap;
}

Why does <pre> not wrap by default?

Because its purpose is to preserve the original formatting exactly, including line lengths and spacing.

What is the difference between pre and pre-wrap?

pre preserves formatting and does not wrap. pre-wrap preserves formatting and allows wrapping.

Will pre-wrap keep indentation?

Yes. It keeps spaces, tabs, and line breaks while still allowing lines to wrap.

Why is my long URL still overflowing inside <pre>?

A single unbroken string may still overflow. Add:

overflow-wrap: break-word;

Should I always wrap code blocks?

Not always. For some code examples, horizontal scrolling is preferred because wrapped lines can make code structure harder to read.

Can I use this for JSON output?

Yes. <pre> with white-space: pre-wrap; is commonly used for formatted JSON and debug output.

Take Quiz

Mini Project

Description

Build a small debug output panel for a web page. The panel will display formatted text inside a <pre> block and use CSS to keep the output readable, even when the content contains very long lines. This demonstrates how to preserve whitespace while allowing wrapping.

Goal

Create a <pre>-based output box that preserves formatting and wraps long debug text cleanly.

Requirements

  • Create an HTML page with a <pre> element for output.
  • Add CSS that preserves formatting and wraps long lines.
  • Insert sample debug text that includes indentation and a very long line.
  • Make sure long unbroken text does not overflow badly.
Take Quiz

Keep learning

Related questions

View more