Home > Blockchain >  How can I get the correct indentation using the HTML <code> element?
How can I get the correct indentation using the HTML <code> element?

Time:10-18

I am creating a documentation page and in one section I attempt to explain the anatomy of the HTML document. In the final outcome, it does not show the correct indentation.

Code:

<p>
   <code>
      &lt;!DOCTYPE html&gt;
      &lt;html lang="en-US" dir="ltr"&gt;
      &lt;head&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;meta name="viewport" content="width=device-width"&gt;
      &lt;title&gt;Title Name&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
      &lt;h1&gt;This is a headline.&lt;/h1&gt;
      &lt;p&gt;1st paragraph.&lt;/p&gt;
      &lt;p&gt;Usually there's quite a lot here.&lt;/p&gt;
      &lt;/body&gt;
      &lt;/html&gt;
   </code>
 </p>

I even added physical indentations and it is still not evident in the final result.

<p>
   <code>
      &lt;!DOCTYPE html&gt;
      &lt;html lang="en-US" dir="ltr"&gt;
        &lt;head&gt;
          &lt;meta charset="utf-8"&gt;
      &lt;meta name="viewport" content="width=device-width"&gt;
      &lt;title&gt;Title Name&lt;/title&gt;
        &lt;/head&gt;
        &lt;body&gt;
          &lt;h1&gt;This is a headline.&lt;/h1&gt;
          &lt;p&gt;1st paragraph.&lt;/p&gt;
          &lt;p&gt;Usually there's quite a lot here.&lt;/p&gt;
          &lt;/body&gt;
        &lt;/html&gt;
   </code>
 </p>

Final outcome

CodePudding user response:

The semantics of the <code> element don't imply that whitespace is significant.

Combine it with a <pre> element (instead of using a paragraph).

CodePudding user response:

This property should be what you are looking for:

code {
    white-space: pre-wrap;
}

CodePudding user response:

Use pre instead of code. The text in pre is "typically rendered using a non-proportional, or monospaced, font. Whitespace inside this element is displayed as written."

CodePudding user response:

A code tag doesn't honor whitespace. The easiest fix is to wrap the code with pre.

<p>
  <pre>
      <code>
     
       ... your code
      </code>
  <pre>
</p>
  •  Tags:  
  • html
  • Related