Open In App

How to wrap a text in a <pre> tag using CSS ?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to wrap a text in a <pre> tag. The <pre> tag is used to display the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. By default, the <pre> tag does not support the <pre> tag. In the case of rendered large text in a prescribed way, the web browsers show a horizontal scrollbar. The user is facing a problem with reading the whole line part by part. 

Approach:

  • First, we create an HTML document that contains a <pre> tag.
  • Now, use the CSS overflow-x property set to “auto” which adds the scrollbar automatically when the contents are overflow.
  • Set the white-space property to “pre-wrap”.
  • At last, use the main word-wrap property which is set to “break-word” so that words that exceed the width of the container will be arbitrarily broken to fit within the container’s bounds.

Example: In this example, we will use the above-explained approach.

HTML
<!DOCTYPE html>
<html>
<head>
    <style>
        #gfg {
            overflow-x: auto;
            white-space: pre-wrap;
            word-wrap: break-word;
            font-size: 15px;
        }

        pre {
            overflow-x: auto;
        }
    </style>
</head>

<body>
    <h2 style="color:green;text-align:center;">
        GeeksforGeeks
    </h2>
    <b>
        How to wrap a text in a &lt;pre&gt; tag?
    </b>

    <h3>
        Before content wrap
    </h3>

    <pre>
            GeeksforGeek,A Computer Science Portal 
            for Geeks. The best courses provided 
            here are best to learn and gain a lot 
            of knowledge related to computer science.
    </pre>

    <h3>
        After content wrap
    </h3>

    <!-- html pre tag starts -->
    <pre id="gfg">
            GeeksforGeek,A Computer Science Portal 
            for Geeks. The best courses provided 
            here are best to learn and gain a lot 
            of knowledge related to computer science.
    </pre>
    <!-- html pre tag ends -->
</body>
</html>

Output:



Next Article

Similar Reads