0

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

IvyAb
  • 1
  • 1
  • Does this answer your question? [How do I use indentation in a tag?](https://stackoverflow.com/questions/21646408/how-do-i-use-indentation-in-a-code-tag) – str Oct 17 '22 at 18:35

4 Answers4

0

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

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

This property should be what you are looking for:

code {
    white-space: pre-wrap;
}
Veso Alex
  • 76
  • 5
-1

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."

Bart Barnard
  • 1,128
  • 8
  • 17
  • 1
    No. The HTML example is code. `pre` should be used **with** `code` (in this case), not instead of it. – Quentin Oct 17 '22 at 18:35
  • Agreed; however, if the question is 'how to keep formatting using whitespace' `pre` would suffice. Another option would, of course, be to replace all spaces with ` `... – Bart Barnard Oct 17 '22 at 18:39
-2

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>
gview
  • 14,876
  • 3
  • 46
  • 51