简体   繁体   中英

Difference between pre(html tag) and white-space:pre newline omission

I thought pre(html tag) active just like 'white-space:pre'. But it's not.

<pre>
aaa
bbb
</pre>

<p style="white-space:pre;">
aaa
bbb
</p>

<pre> ignore the first and last \\n . But <p> keep the first \\n and ignore the last one. Why?

jsfiddle test

The HTML standard states:

Note: In the HTML syntax, a leading newline character immediately following the pre element start tag is stripped.

Read here: http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#the-pre-element

So, the <pre> element contains this special rule. It seems that if other types of elements have a white-space:pre setting, that rule doesn't apply.

Actually, they are the same. The reason you're getting the space on top for <p> s is because by default <p> adds an empty line above itself so that you can distinguish between paragraphs. <pre> doesn't do that, so you get no extra space there.

The <pre> -Tag displays the content with a monospace font, wich means that every character has the same width.

It is easier to read instead of the standard-font of the browser, used in the <p style="white-space:pre;"> .

The HTML pre element and the CSS setting white-space: pre are quite distinct constructs; it is a category error to confuse the two. But you seem to be referring to a difference in rendering as regards to line breaks.

By the specifications , a line break immediately following a start tag shall be ignored, so

<pre>
aaa
bbb
</pre>

should be equivalent to

<pre>aaa
bbb
</pre>

and this should not change in any way if p is substituted for pre or some styling is added. But browsers don't always play by the rules, and this is one of the cases.

They just treat elements differently. The morale is that you should avoid using the pre element as well as white-space: pre , and if you used them, stay tuned to this variation. When needed, do not follow the start tag immediately by a line break but a space and a line break (if you want to have an empty line at the start).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM