HTML 中的代码格式缩进出现在文档中

这是我从 Anki(抽认卡创建程序)复制并粘贴的 HTML 代码。该代码运行良好。(背景:抽认卡是一道编程题)

<meta content="width=window-width, initial-scale=1.0" name="viewport">

浏览器上渲染的代码:

https://img1.mukewang.com/64e349cf0001831f06290154.jpg

显然,该代码以当前格式不可读。为了解决这个问题,我添加了适当的缩进。


<meta content="width=window-width, initial-scale=1.0" name="viewport">


What does this code do?

<div>

  <div background-attachment:="" background-clip:="" background-image:="" background-origin:="" background-position:="" background-repeat:="" background-size:="" class="highlight" initial;="" initial;"="">

    <pre style="line-height: 25px;">

      <table class="highlighttable" style="font-family: Arial;">

        <tbody>

          <tr>

            <td>

              <div 10px"="" class="linenodiv" padding-right:="">

                <pre style="line-height: 125%">1</pre>

              </div>

            </td>

            <td class="code">

              <div class="highlight">

                <pre style="line-height: 125%">&lt;<span style="color: #008000; font-weight: bold">meta</span> <

                  span style="color: #7D9029">http-equiv</span>

                  <span style="color: #666666">=</span>

                  <span style="color: #BA2121">"X-UA-Compatible"</span>

                  <span style="color: #7D9029">content</span>

                  <span style="color: #666666">=</span>

                  <span style="color: #BA2121">"IE=edge"</span>&gt;

                </pre>

              </div>

            </td>

          </tr>

        </tbody>

      </table>

    </pre>

  </div>

  <div>

    <center>

      <br>

    </center>

  </div>

</div>

奇怪的是:上面的缩进现在出现在 HTML 文档中。

https://img.mukewang.com/64e349ea000198f506480374.jpg

这不应该发生,对吗?我认为 HTML 中的换行符对用户不可见?



繁花如伊
浏览 75回答 1
1回答

慕桂英4014372

那是因为whitespaceis pre(由浏览器保留)。这样做的目的是为了让您可以缩进代码。通常,当您想要在 HTML 中呈现代码时,您可以取消缩进:            <td class="code">              <div class="highlight">                <pre style="line-height: 125%">&lt;<span style="color: #008000; font-weight: bold">meta</span><span style="color: #7D9029">http-equiv</span><span style="color: #666666">=</span><span style="color: #BA2121">"X-UA-Compatible"</span><span style="color: #7D9029">content</span><span style="color: #666666">=</span><span style="color: #BA2121">"IE=edge"</span>&gt;                </pre>              </div>            </td>请注意,您不需要在行<pre>本身上执行此操作(这就是元部分显示您所需的缩进的原因)。如果您要经常使用代码片段,像 Prismjs这样的库将使您的生活变得更加轻松并且值得花费这些开销(事实上,这是一个非常轻量级的库):<pre><code class="language-html">(... html code ...)</code></pre>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5