How to Wrap Text in a <pre> Tag with 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.
<!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

  • Set the overflow-x property to "auto".
  • Set the white-space property to "pre-wrap". Also, use the -moz- and -o- prefixes with the value.
  • Add the word-wrap property with the "break-word" value.
pre {
  overflow-x: auto;
  white-space: pre-wrap;
  white-space: -moz-pre-wrap;
  white-space: -pre-wrap;
  white-space: -o-pre-wrap;
  word-wrap: break-word;
}

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;
        white-space: -moz-pre-wrap;
        white-space: -pre-wrap;
        white-space: -o-pre-wrap;
        word-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

         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...