If you are displaying code on a website that is longer than a few lines it gets hard to read without proper code highlighting.
For my code examples I’m using prism to make my code more readible.
It is very easy to integrate into your website. First go to prismjs.com/download.html and configure which languages you need. You should only select the languages you are really going to use as the css file gets very big with too many languages.
After the configuration you can download two files:
First you should minify the css file to make it a little bit smaller. Make sure that you don’t remove the comment at the top of the file as it mentions the author.
There are a lot of online tools that will do the minification for you.
After minifying you can add the two files to your website.
<link href="themes/prism.css" rel="stylesheet" />
The stylesheet should be added in the
<head> -section of the page
</body>-tag as possible.
How to use prism for code highlighting
Whenever you post code to your page you encase it in a <pre>- and a <code>- tag like this:
<pre> <code class="language-html"> <!-- Your code here --> </code> </pre>
Two more thing to take care of:
- The class-name has to match the language you are displaying. To display css-code you would use the class-name “language-css”.
- The special characters of your code have to be escaped. If you are using a CMS like wordpress your content-editor is most likely doing this automatically.
If not there are a lot of free online-generators which will do the job for you.
Line numbers and language tag for prism code highlighting
Especially for longer source code it makes sence to add line numbers to the code. You can see an example with the HTML-Code above.
That way it is easier to reference a certain line when you want to explain it.
To achieve this with prism you have to do two things:
- Add the line numbers plugin when configuring prism.
- Add the class
To add a language tag add the class
<pre> <code class="language-html line-numbers language-markup"> <!-- Your code here --> </code> </pre>
Different colors schemes for code highlighting
Prism even offers diffrent predefined color settings you can choose from. If you are interested in that comment below and I will add a follow up to this article.