25 Apr 2020

HTML - Preserve text formatting such as paragraph breaks

In HTML when you want to display text generally the paragraph <p> tag is used. However, if the text you wish to display has spaces between paragraphs (carriage returns), using <p> will remove those, making your text look like just one long string of words - ugly!

The solution is to use the <pre> tag instead of <p>. The <pre> will retain any basic formatting. 

For example:

Using <p>


Appears in a browser as follows:




Using <pre>



Appears in a browser as follows:




Conclusion
Using <pre> allows the text to appear as it was originally written. This can be very useful, especially if you are parsing text from one source to another and wish to display that text in a browser.

But it's important to realise that <pre> takes care of basic formatting, it doesn't handle rich text. It's just the spacing and line breaks (carriage returns). If you have more sophisticated source formatting you'll have to look at more sophisticated solutions such as CSS.


References
More details here:
https://www.w3schools.com/tags/tag_pre.asp



No comments: