简体   繁体   中英

How do I use indentation in a <code> tag?

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.

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

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 .

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 (eg, 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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM