12

I have a code tag with some computer code:

<code>
    int main(){  <br/ >
        printf("Hello World!");<br/ >
    }
</code>

But when I display it in the browser, there will be no indentation. How can I do this, besides using &nbsp;? Writing them would be a very tedious job.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • 1
    `pre` might be useful? – godfrzero Feb 08 '14 at 13:15
  • Possible duplicate of [How to preserve whitespace indentation of text enclosed in HTML
     tags excluding the current indentation level of the 
     tag in the document?](https://stackoverflow.com/questions/4631646/how-to-preserve-whitespace-indentation-of-text-enclosed-in-html-pre-tags-exclu)
    – mikemaccana Apr 16 '18 at 14:13

3 Answers3

16
<pre>
    <code>
        int main(){  
            printf("Hello World!");
        }
    </code>
</pre>

You can use the "pre" tag, which defines preformatted text. Text in a "pre" element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks. It is used when displaying text with unusual formatting, or some sort of computer code. And you will not need additional "br" tags.

Your code should look like the above one.

You can find more about the tag here.

str
  • 42,689
  • 17
  • 109
  • 127
4

The code element does not change normal HTML formatting rules, which collapse consecutive whitespace to a single space. It does not do much else either, beyond setting the font to monospace by default, though in special cases it may have some effect (e.g., automatic translation software might treat code elements so that their content is left untranslated).

You could use CSS to request different formatting:

<style>
code { white-space: pre }
</style>

But this is unnecessarily fragile (CSS rules might be ignored for various reasons), when you can simply use the pre element (and remove the br tags):

<pre>
    int main(){  
        printf("Hello World!");
    }
</pre>

If you wish to additionally use the code element for some reason, then the valid way is to nest code inside pre, not vice versa. Here you then need to notice that special rules about ignoring a line break after a <pre> tag do not apply here (since there would be an intervening tag), so to avoid getting an extra line break at the beginning, you would need to write like this:

<pre><code>   int main(){  
        printf("Hello World!");
    }</code></pre>

P.S. Neither code nor pre changes the rules about the markup-significant characters < and &, which should be encoded as &lt; and &amp;, respectively. For example, text like a<b&c would need to be written as a&lt;b&amp;c.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
2
<code>
<pre>
    int main(){  <br/ >
        printf("Hello World!");<br/ >
    }
</pre>
</code>