理解 HTML 中的 pre 标签


#Web 前端开发#


HTML 的 <pre> 标签会将其包含的内容原封不动的展示出来

下面的的示例中引入了boostrap 的css文件作为辅助,使用军蓝色(cadetblue)作为 class 为 container 的div的背景色:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            margin-top: 100px;
            background-color: cadetblue;
        }
    </style>
</head>
<body>

<div class="container">
<pre>
12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'
</pre>
</div>

<div class="container">
<pre>12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'</pre>
</div>

</body>
</html>

在谷歌浏览器中效果如下:

可见,<pre>所在行若<pre>之后有内容(空格也算内容),则将内容展示在第1行。若<pre>之后无内容,则以<pre>下一行内容展示为第1行。 类似的,</pre>所在行若</pre>之前有内容(空格也算内容),则将内容展示在最后一行。若</pre>之前无内容,则以</pre>上一行内容展示为最后一行。

如果每一行之前有空格:

<div class="container">
<pre>
    12
    print 'hi'
    print 'hello hello hello hello hello hello hello hello hello hello hello'
</pre>
</div>

那么空格也会被浏览器展示出来:

如果要让浏览器展示出<>,``pre的代码中需要写成 <>`。如果 pre 标签的内容中有其他的 HTML 标签,浏览器会将他们作为标签处理,而不是原封不动的展示出来。例如:

<div class="container">
<pre>
<code>
&lt;12&gt;
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'
</code>
</pre>
</div>

<div class="container">
<pre>
<code>12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'</code>
</pre>
</div>

效果如下:

为什么第1个代码块,第一行和最后一行是空行?因为<code></code> 标签单独占了一行,它们所在行的末尾都有一个回车符。

pre 内部支持其他的html标签,那么自然支持这些标签的渲染效果:

<div class="container">
<pre>
    <strong style="color: green">12</strong>
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'
</pre>
</div>

效果如下:


( 本文完 )