How to syntax highlight code blocks in your blog or website

Published: 1 year ago - Updated: 1 year ago

1 minute - 206 Words

article 'How to syntax highlight code blocks in your blog or website' banner

Summary

In this blog post you will learn how to syntax highlight your <code> blocks for your blog or tech website using Highlight JS Library.

What is highlight.js ?

Highlight JS is a Syntax highlighting library for the Web. It is a lightweight library with following features:

  • Supports 196 languages and 242 styles
  • Automatic language detection
  • Multi-language code highlighting
  • Works with any markup
  • Compatible with any JS framework

How to use highlight.js ?

The bare minimum for using highlight.js on a web page is linking to the library along with one of the themes and calling highlightAll().

A prebuilt version of highlight.js with 34 commonly used languages is hosted by following CDNs.

Add the css to your page

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/default.min.css" >

Add the js to your page

<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/highlight.min.js"></script>

Add the your code snippet inside ‘pre’ and ‘code’ tag

<pre> 
   <code class="language-javascript" >
      const [loading,setLoading] = React.useState(false);
      getData = () => {
          // get the data from api
      }
   </code>
</pre>

As I mentioned above Highlight JS can automatically detect the language but can you specify the language explicitly by adding the class name “language-{language}” i.e class=“language-html” , class=“language-json” .

Finally Call the highlightAll() function

<script>  hljs.highlightAll(); </script>

The result will be something like this (your output’s theme might not match my result)

const [loading,setLoading] = React.useState(false);

getData = () => {
    // get the data from api
 }

Link to Official Highlight JS page
highlight.js

Add Comment

Conversations (0)

Sign up for our newsletter

Stay up to date with the latest news and articles.