Display element as preformatted text via CSS

Dagg Nabbit picture Dagg Nabbit · Mar 17, 2012 · Viewed 59.8k times · Source

Is there any way to emulate the display of a pre element via CSS?

For example, can I keep the whitespace intact in this div by using a CSS rule?

<div class="preformatted">

  Please procure the following items:

    - Soup
    - Jam
    - Hyphens 
    - Cantaloupe
</div>

Answer

BoltClock picture BoltClock · Mar 17, 2012

Use white-space: pre to preserve whitespace preformatting as in the pre element. To go a step further, also add font-family: monospace, as pre elements are typically set in a monospace font by default (e.g. for use with code blocks).

.preformatted {
    font-family: monospace;
    white-space: pre;
}
<div class="preformatted">

  Please procure the following items:

    - Soup
    - Jam
    - Hyphens 
    - Cantaloupe
</div>