Home »
CSS
How to wrap text in a pre tag using CSS?
In this tutorial, we will learn how to wrap text in a pre tag using CSS with the help of example. Given text within a <pre> tag, we have to wrap text within in the <pre> tag.
By Apurva Mathur Last updated : July 15, 2023
Let's initiate the topic by learning what a <pre> tag is all about.
<pre> Tag
It is also known as preformatted text. The text written inside this tag would display as it is, by default browser ignore all kind of spaces or line breaks that are specified in the HTML but if we want to display the text just the same so we can use this <pre> tag.
Example showing how to use <pre> tag in HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body style="background-color:lavender">
<pre style="font-size: 20px;color: black;font-weight: bold;font-family: 'Baskerville Old Face'">
Everyone in this world craves for a happy life.It is difficult to define happiness as it is a state of the mind and it is subjective.Happiness is related to material glory and splendour by some.
Some associate it with the health of a man while for some it lies in a sort of contentment with whatever one possesses.
</pre>
</body>
</html>
Output:
We can clearly see that text displayed is same as text written in HTML file.
How to wrap text in a pre tag using CSS?
To wrap text in a <pre> tag using CSS, you can use the CSS properties like overflow-x, white-space, and word-wrap with the given values:
- overflow-x: auto;
- white-space: pre-wrap;
- word-wrap: break-word;
CSS to wrap text in a 'pre' tag
pre {
overflow-x: auto;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
Now let us see how to wrap text in a <pre> tag.
Example to wrap text in a 'pre' tag using CSS
<html>
<head>
<style>
pre {
overflow-x: auto;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
</style>
</head>
<body>
<h1>Pre tag after wrapping the text</h1>
<pre style="font-size: 20px;color: #222222">
Everyone in this world craves for a happy life.
It is difficult to define happiness as it is a state of the mind and it is subjective.
Happiness is related to material glory and splendour by some.
Some associate it with the health of a man while for some it lies in a sort of contentment with whatever one possesses.
</pre>
</body>
</html>
Output:
CSS Examples »