< Day Day Up > |
Occasionally, spacing, tabs, and returns are so important in text that HTML's default behavior of disregarding them would ruin the text's meaning. In such cases, you might want to preserve the intended formatting by specifying the text to be preformatted. Imagine that programming source code or poetry needs to be inserted into a Web page. In both cases, the spacing, returns, and tabs in the document must be preserved to ensure proper meaning. This situation requires an HTML directive that indicates the preservation of format. The <pre> tag can be used to indicate text that shouldn't be formatted by the browser. The text enclosed within a <pre> tag retains all spacing and returns, and doesn't reflow when the browser is resized. Scrollbars and horizontal scrolling are required if the lines are longer than the width of the window. The browser generally renders the preformatted text in a monospaced font, typically Courier. Simple forms of text formatting, such as bold, italics, or links, can be used within <pre> tags. The following example, displayed in Figure 3-6, uses the <pre> tag and compares it to regular paragraph text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <title> Pre Example </title> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> </head> <body> <pre> This is P R E F O R M A T T E D T E X T SPACES are ok! So are RETURNS! </pre> <hr /> <p> This is NOT P R E F O R M A T T E D T E X T SPACES and RETURNS are lost. </p> </body> </html>
Note | According to the HTML and XHTML specifications, only certain HTML elements are allowed within the <pre> tag, and some elements, such as <img> , are excluded. Most browsers allow any elements, even those beyond the stated specification, to appear within <pre> , and render these as expected. Authors should not, however, rely on this. See Appendix A for the <pre> tag's content model. |
HTML authors should be careful about using <pre> to create simple tables or preserve spacing. Unpredictable differences in browser window sizes could introduce horizontal scrolling for wide preformatted content. In these cases, other elements, particularly <table>, will provide better formatting control.
< Day Day Up > |