How to display raw HTML code on an HTML page
When you wish to display HTML code on a webpage without rendering it, you have to "escape" certain characters. In HTML, you do this by replacing <
, >
, and &
with <
, >
, and &
respectively. Here's an example:
When enclosed within the <pre>
tag, the code maintains its original formatting - preserving all the spaces and line breaks that you've typed in the source code.
HTML escaping tactics
Escaping involves replacing &
, <
, and >
with &
, <
, and >
. While >
does not always require escaping, replacing it maintains consistency and improved readability.
Deprecated elements: oldies but not goldies
It's highly advised not to use <textarea>
or <xmp>
for displaying HTML code. These are all but obsolete now, and their use can lead to a messy output and render your HTML incorrectly across different browsers.
<pre>
and <code>
: the classic duo
The common practice for presenting a block of code on an HTML webpage is to wrap the content inside a set of <pre>
and <code>
tags. In this way, your code's formatting is preserved and it appears as a block of preformatted code.
The <pre>
tag: keeping things simple
For a simplified display of preformatted text, using only the <pre>
tag might do the trick. It won't give the semantic importance of the <code>
tag does, but it will certainly hold its ground by preserving the white spaces, tabs, and line breaks.
Quoting with <blockquote>
You want to showcase a block of HTML in your text as a citation or quotation? <blockquote>
is here for the rescue. It not only displays the quoted HTML, but also adds a semantic connotation to it as a citation.
Handling XHTML: XML’s cousin
In case you're working with a XHTML document or some XML-specific cases, it's possible to preserve an HTML code snippet without escaping characters by using CDATA sections. Remember to serve it under the right Content-Type
.
Automation: let machines do the dirty work
Manually escaping characters might be a daunting task. Thankfully, we have at our disposal a variety of automated tools, such as server-side libraries or JavaScript functions that accomplish this task effortlessly.
It’s recipe time!
To help you understand better, here're some recipes from the coding kitchen in various situations. Enjoy! 🥦🔪
- Plain HTML Display:
- Inline code:
- Blockquote:
- XHTML CDATA section:
Cutting edge tools and libraries
Your code can be simply colored using syntax highlighting libraries like highlight.js
or Prism
. They can give a major visual upgrade to your code snippets.
Was this article helpful?