Render HTML String Preserving Spaces and Line Breaks



Sometimes while writing the content of an HTML file, there might be the need to preserve blank spaces and line breaks. You might have noticed when you try to write something in the paragraph <p> tag or the <div> tag that has a lot of white spaces or a line break, it is not visible when the HTML page is rendered in the web browser. This article will show how to preserve those spaces while rendering the HTML page.

Render an HTML String Preserving Spaces and Line Breaks

Using Pre Tag

One method to preserve spaces and line breaks is using the pre-formatted HTML tag <pre>. It displays the text in a fixed-width font and displays the text as it is written in the HTML code enclosed within the <pre> tag.

Example

<!DOCTYPE html>
<html>
<body>
    <h3>HTML String Preserving Spaces and Line Breaks</h3>
    <pre>
        Hello world!
        Welcome to Tutorialspoint.
            Today we are learning about preserving
          spaces and line
        breaks in HTML.
    </pre>
</body>
</html>

Output


Using white-space Property

Another method is to use styling. This can be used with any HTML element, that is, paragraph <p> tag, <div> tag, and <span> tag. We just need to specify the style attribute and define white-space as a pre-wrap.

Example

<!DOCTYPE html>
<html>

<body>
    <h3>HTML String Preserving Spaces and Line Breaks</h3>
    <div style="white-space:pre-wrap;">
        Hello World!
        Welcome to Tutorialspoint.
            Today we are learning about preserving
          spaces and line
        breaks in HTML.
    </div>
</body>

</html>

Output


Tanya Sehgal
Tanya Sehgal

Python and HTML

Updated on: 2024-09-30T09:54:39+05:30

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements