Displaying Preformatted Text in HTML

Sometimes, it is useful to display text the way you have formatted it. The <pre> element allows you to do this. It supports global attributes, and the content can be styled using CSS. It is a block-level element, and its content is rendered by default in monospace font, with leading space preserved and a margin of about 1 em added at the top and bottom edges. Figure 3.28 shows how the element is used, and Figure 3.29 depicts the result.

Notice in the example that the content of the <pre> element is as it is in the HTML source. Also, notice that the element is inside the <p> element. However, it does not have to be; the text above and below it can be in separate <p> elements. Moreover, note that even though the <code>, <kbd>, and <samp> elements are, by default, rendered in monospace font, they should not be used in place of the <pre> element, as the element is recognized by user agents to have a specific meaning and is treated appropriately.

Use the <pre> element in the same body of text as the <code> <kbd> and <samp> elements to compare the outputs.

Source: Sklar David (2016), HTML: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *