Display element as preformatted text via CSS [dupl

2019-01-13 06:43发布

问题:

This question already has an answer here:

  • How to change a span to look like a pre with CSS? 7 answers

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>

回答1:

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>



回答2:

.preformatted {
   white-space: pre-wrap;
}

I think "pre-wrap" is better. It can help with long length in line.



回答3:

Yes:

div.preformatted {
    white-space: pre;
    }

Reference:

  • white-space.


回答4:

inorder to get <pre> you may use;

div.preformatted{ white-space: pre ; display: block; }