How to keep natural spaces and line breaks like poems using preformatted text in HTML

What is HTML Preformatted Text?

In HTML, <pre> (preformatted text) element is used to define text that preserves both spaces and line breaks within the text in a webpage.

The <pre> element is commonly used when displaying code snippets or poems like text or any text where maintaining the original formatting, such as indentation, is important.

Please note that you should not use <pre> for displaying regular text in a webpage.

Example of Creating HTML Preformatted Text

Create an HTML <pre> element to your webpage.

Add your text between the <pre> and </pre> tags as shown in the following example.

In the following example, "Twinkle, Twinkle, Little Star", a popular English lullaby, is added to display the text format of poem with natural spaces and line breaks.

Example of Preformatted Text


Output of the above example

	Twinkle, twinkle, little star

	How I wonder what you are

	Up above the world so high

	Like a diamond in the sky

	Twinkle, twinkle little star

	How I wonder what you are
    

You can display code snippets of programming languages using HTML preformatted text in a webpage.

The following example illustrates the display of code snippets of C# programming language.


Output of the above example

    using System;

    namespace ExampleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!"); // The output is "Hello World!"
            }
        }
    }

Live Code Playground

In the following HTML code editor, you can practice the above code by creating more new HTML preformatted text. Click on the 'Run Code' button to render the code; the rendered page will be displayed in the following HTML Code Output frame. Practice until you become comfortable and proficient with your code.

HTML logo HTML Online Editor
HTML Code Output