03/11

Adding Syntax Highlighting to your website

So today I encountered a problem that many might have faced already, while blogging code is that there is no default syntax highlighting and it was completely spoiled when using normalize.css.

Syntax Highlighter

My first preference was using the Syntax Highligher. Also, I didn't want to add any more JS calls to my server so I found its cdn and tried hosting. Everything was included as the websites instructions and still there was no highlighting working on the code blocks. Later I realized that it wasn't detecting the code automatically unless a class name was appended.

Now, that I'm using markdown to write my blogs and I didn't want to shift to manually editing my pre tags so I skipped this approach altogether.

Highlight.js

The second attempt was with a rather easy to use syntax highlighter, which unlike syntax highlighter worked seamlessly. Highlight.js also has its cdn hosted at cdnjs.com which made it easy to setup.

The only code I had to add was as specified by the usage page and not a single line more. The final code ended up looking like this

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/github.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

Yep, just that and all my code blocks were beautifully highlighted.

Code Tag Style

My only problem with this was that no inline code blocks were styled at all, which made them look really huge and ugly. This was solved by using a simple css snippet, which I found here.

code {
  padding: 0.2rem 0.1rem;
  color: #333;
  background-color: #f8f8f8;
  text-shadow: 0 0 0.2rem #fff;
  font-size: 0.9rem;
  font-weight: lighter;
  font-family: Monaco,'MonacoRegular',monospace;
}

I manipulated the color to match the one given by the github.min.css up there to maintain some uniformity.

Tweet your views, comments or any problems you encounter @sidharathc

Image Credits: Unsplash

END
UP NEXT