HTML Pre Tag

HTML Pre Tag

Many a time, we might require to retain the spaces and newlines that occur in the text, like if we are putting some python code into our web page, the spaces (indents) have totally different importance, and they need to be retained. If we are in such a situation, the pre-tag is there for our escape.

Well, the pre-tag is used to define the preformatted text. By this, we mean that the text will be shown in a fixed-width font, preserving the line breaks and the spaces. We can say that the text will be shown as it is written into the source code.

If you try to put some spaces, or press enters into some other elements like div, span or p, etc, you will find that the spaces and the new line things are ignored. Refer to the below example, which demonstrates the same thing –

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Some heading…</title>
</head>
<body>
<div>

We are inside a div right now…
this is supposed to be on the next line…

This is far away…
    </div>
</body>
</html>

You know what output we are expecting, but, this is what we get –

Strange right? But this is what I was talking about… the new lines, and the spaces were ignored. If the spaces and the new lines are important to us, we can put the text in the pre-tag instead. With the pre-tag, the text will be displayed in the fixed-width font, and the spaces and the line breaks will be retained. In short, the text will be displayed as it is written in the source code. Have a look at the below example, where we are using the pre-tag –

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Some heading…</title>
</head>
<body>
<pre>

We are inside a pre right now…
this is supposed to be on the next line…

This is far away…
    </pre>
</body>
</html>

So, now, if we try to open the file in the browser, the output is something like this-

Notice that the spaces and the new lines are retained. In fact, the font is also different this time. But where would we need this tag? Well, let’s discuss one use case. Let’s say that you have a website, where you need to add some code snippets, related to

python(don’t worry if you are not familiar with python, we are not going to get into it here anyways, but if you are familiar with python, it is good). The thing is, the indentations(tabs) are very important in python. So, you will want your code to be displayed just as it is right? So, by putting the code into the pre-tag, the tabs and new lines will be retained as it is.

By the way, there is another element called code, which is going to be discussed further, but it is used to define the code, or something computer understandable.