How do I insert code examples into an HTML file?

The <pre> tag allows you to display text with whitespaces and line breaks as-is. Also, code must be entity-encoded: For example, the code sample

 <html>
   <head><title></title></head>
   <body></body>
 </html>

will become

<pre>&lt;html>
  &lt;head>&lt;title>&lt;/title>&lt;/head>
  &lt;body>&lt;/body>
&lt;/html></pre>

< encodes into &lt; & encodes into &amp;

PHP htmlentities does the job:

<pre><?php echo htmlentities($code) ?></pre>

<textarea> does the job too: it also allow the code to be copied.


Xmp tag will work:

<xmp>
   ...code...
</xmp>

ETA: As of this writing this still works in all major browsers, but as others have pointed out it has officially been obsoleted in HTML5 [link]. Browsers could stop rendering it any day without warning or notice and it should be avoided for production sites. Still, there is no replacement that doesn't involve HTML encoding your string manually or using iframe trickery. It still has a place in my personal utility page tool-belt, but I would not consider it for a client.


To present code in HTML typically one would use the <code> tag.

Your question isn't very clear, and I don't know what you mean by "without the tags being processed". If you're saying that you want to present a fragment of HTML as code in an HTML page (for example), then you need to "escape" the HTML tags so that the web client doesn't attempt to parse them.

To do this, you should use the entity &gt; for the greater-than angle bracket, and &lt; for the less-than bracket.

Tags:

Html