Pre Tag

 

Pre Tag

The <pre> tag serves as an indispensable tool in HTML for displaying preformatted text, such as code snippets in various programming languages.

What Does the <pre> Tag Do?

The <pre> tag preserves the original formatting of text, making it an excellent choice for displaying code where spacing and indentation are key.

Syntax for Using the <pre> Tag

<pre>
    <!-- code snippet in any programming language -->
</pre>

Key Features

  • The <pre> tag maintains both spaces and line breaks, ensuring that text appears exactly as it was originally formatted.
  • The <pre> tag has both an opening tag <pre> and a closing tag </pre>.
  • Additional attributes can also be added for further customization.

When to Use the <pre> Tag?

The <pre> tag is most effective when you want the text to display on your HTML page exactly as it was typed, without any formatting changes. It is especially useful for displaying code snippets or preformatted text from data files.

Displaying a Simple Python Program and Its Output

In this section, we will use HTML to display a simple Python program that prints 'Hello, World!' to the console. Don't worry, you don't need to know Python; we're just showing how to display the program using the HTML <pre> tag.

Python Program

<pre>
  # A simple Python program to print "Hello, World!"
def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()
</pre>

Program Output

This HTML code will display the program exactly as it is, preserving spaces and new lines. We'll use the <pre> tag to achieve this 'preformatted' display, as shown below.

 # A simple Python program to print "Hello, World!"
  def main():
      print("Hello, World!")

  if __name__ == "__main__":
      main()
 

For a more comprehensive understanding, you can watch the following video tutorial:

Conclusion

In summary, the <pre> tag is a versatile tool for preserving the original formatting of text in HTML. Whether you are displaying code snippets or preformatted text, this tag ensures that your content appears exactly as intended.