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 <
for < and >
for > which gives you the result you want.
Cover image by Jackson Sophat on Unsplash
This is really a helpful guide; thanks for sharing.
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.
Congratulations @learningpages! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)
Your next target is to reach 2500 upvotes.
You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word
STOP