Home | Anecdotes | Articles | Icebreakers | Programs | Quotations | ShopDashboard | Log in | Sign up

How to Display Code in HTML


Image by Jackson Sophat on Unsplash

Displaying code snippets in HTML is not as straightforward as I first thought. Surely it's just a matter of adding <code> tags? However, when I started including code in my programming articles, I found that I needed to do more than just adding <code> tags to make it work and look good.

I'll start with a simple example:

if (x == y) {
  print("x equals y");
}

<code> tags

The usual way of doing this in HTML is to add <code> tags:

Adding this code to an HTML page, gives you the following result:

There are no line breaks! You could add <br/> tags at the end of each line, but this can involve a lot of work.

<pre> tags

A simpler and better way is to use <pre> tags which preserve both spaces and line breaks.

This is how it looks on an HTML page:

Although the layout is correct, the code is dull, small and not easy to read.

Syntax highlighting

This can be improved with syntax highlighting. Syntax highlighting uses different colours for keywords, variables and strings etc. It is possible to do this with CSS, but I prefer to use a library like Prism.js

To do this, you need to include the Prism.js library in your HTML page by inserting...

<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/themes/prism.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/prism.min.js"></script>

...in the <head> element of the your HTML page and adding class="language-javascript" to every <code> tag. This gives a much better result:

Delimiters

The symbols '<' and '>' are examples HTML delimiters. They don't cause problems unless you are displaying HTML markup code.

If you were to display the following using the <pre> and <code> tags...

<p>
Some HTML code with a <p></p> element<br/>
and a line break.
<p>

...you would get the following result:

The problem here is that the browser interprets the tags as HTML even though they are enclosed in <pre> and <code> elements.

The way round this is to use &lt; for < and &gt; for > which gives you the result you want.

Originally posted by Learning Pages in Programming and Dev

More Programming articles
🍯 Leave a tip
78   64


About Learning Pages | Support us