W3docs

How to Wrap Text in a <pre> Tag with CSS

The <pre> tag inserts a preformatted text into an HTML document. Since the <pre> tag doesn’t support wrapping, we’ll show how to do it with the help of CSS.

The HTML <pre> tag is used for inserting a preformatted text into an HTML document. It preserves the spaces and line breaks of the text. This tag is commonly used to display code or a text, where the author himself sets the location of the lines.

The <pre> tag doesn’t support wrapping, by default. That’s why the browser will display a horizontal scrollbar when rendering a large line. In this case, you will be able to read the whole line part by part using that scroll bar.

To overcome the problem described above, you’ll need to use CSS. Let’s see how to do it.

Create HTML

  • Use a <pre> tag and place text inside.

How to Wrap Text in a <pre> Tag with CSS

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <pre>
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s...
    </pre>
  </body>
</html>

Add CSS

How to Wrap Text in a <pre> Tag with CSS

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

The pre-wrap value preserves original line breaks and spaces but allows text to wrap onto the next line when it reaches the container's edge.

Now, we can see the result of our code.

Example of wrapping a text inside a <pre> tag:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
pre {
  overflow-x: auto;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}
    </style>
  </head>
  <body>
    <pre>
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s...
    </pre>
  </body>
</html>

Result

<div class="demo not-prose"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s... </div>