Open In App

HTML pre Tag

Last Updated : 20 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The pre tag in HTML defines a block of preformatted text, preserving spaces, line breaks, and tabs. It displays text in a fixed-width font, which can be styled using CSS. This tag is useful for displaying code, formatted text, and preserving text layout.

HTML
<!DOCTYPE html>
<html>

<body>
    <pre>
        This    is      preformatted
        text.
        It preserves spaces and
        line breaks exactly.
    </pre>

</body>

</html>

The <pre> tag is a powerful tool for preserving the exact formatting of text within a web page. By using the <pre> tag, along with related tags like <samp>, <var>, <code>, and <kbd>, you can effectively display preformatted text, sample outputs, variables, code snippets, and keyboard inputs in a visually appealing and semantically meaningful way. Customizing the appearance of the <pre> element with CSS further enhances its versatility and integration into your web design.

Note: The pre tag also supports the Event Attributes in HTML and Global Attributes in HTML.

Tag

Description

<samp>

Defines sample output from a computer program

<var>

Defines a variable

<code>

Defines a piece of computer code.

<kbd>

Defines keyboard input

Using CSS with the <pre> Tag

HTML
<!DOCTYPE html>
<html>

<body>
    <pre style="font-family: Arial;color: #009900;margin: 25px;">
        This    is      preformatted
        text.
        It preserves spaces and
        line breaks exactly.
    </pre>

</body>

</html>

HTML <pre> Tag – FAQs

How does the <pre> tag handle whitespace?

The <pre> tag preserves all whitespace characters, including spaces, tabs, and line breaks. This is different from most HTML elements, which collapse multiple spaces into a single space and ignore line breaks.

Can I use the <pre> tag for displaying code?

Yes, the <pre> tag is commonly used to display code snippets in a readable format. It is often combined with the <code> tag for semantic purposes.

What is the difference between the <pre> tag and the <div> tag?

The key difference is that the <pre> tag preserves whitespace and line breaks exactly as they are in the source code, while the <div> tag does not. The <pre> tag is used for content where formatting needs to be maintained, while the <div> tag is used for general block-level content.

Can I include HTML elements inside a <pre> tag?

Yes, you can include other HTML elements like <b>, <i>, or <span> inside a <pre> tag. However, it’s most commonly used with text or code to maintain formatting. Be cautious with elements that could disrupt the formatting you’re trying to preserve.

Is the <pre> tag a block-level or inline-level element?

The <pre> tag is a block-level element, meaning it takes up the full width available and starts on a new line by default.


Next Article

Similar Reads

three90RightbarBannerImg
  翻译: