Code highlighting on Website in pre- or code- tag

0
104

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:

  • prism.css
  • prism.js

Integrating prism

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.

CSS

<link href="themes/prism.css" rel="stylesheet" />

The stylesheet should be added in the <head> -section of the page

HTML

<script src="prism.js"></script>

The javascript file should be included as close to the closing </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:

  1. The class-name has to match the language you are displaying. To display css-code you would use the class-name “language-css”.
  2. 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

Prism code highlighting Line Numbers and Show language
Configuring Prism code highlighting Plugins, adding Line Numbers and Show Language

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:

  1. Add the line numbers plugin when configuring prism.
  2. Add the class line-numbers to the <code>-tag.

To add a language tag add the class language-markup.

<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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here