Syntax highlighter highlight.js

busy city street in tropical town at night
Reading Time: 2 minutes

highlight.js it’s an awesome library to highlight code from several languages. With an easy-to-customize aesthetic. It’s very straightforward to add it to any project: just include the library, the stylesheet, and set up a <pre> tag with HTML. After that, wrap any code snippet with either the <pre> tag and add a <code class="language-name"> classic class. The library will take care of the rest!

Highlight.js supports over 180 languages in the core library. List of supported languages

The official site of highlight.js: https://highlightjs.org/

example of syntax highlighting by highlight.js
Example of syntax highlighting by highlight.js

How to install highlight.js

Download the styles and include it between the <head></head> tags:

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

Import the script at the end of the body tag

<body>
  ...
  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script>
</body>

How to use highlight.js

<pre><code class="language-javascript">
const myConst = "example"
</code></pre>

How to highlight XML with highlight.js

If you want to highlight you will have to escape the brackets with:

&lt; and &gt;

Example:

<pre><code class="xml">
  &lt;my-tag&gt; my content &lt;/my-tag&gt;
</code></pre>

Custom dark mode syntax highlighter for highlight.js

It’s possible to override the default styles. Let’s say you want a dark mode, you can use these styles and modify the colors as needed.


/* custom hljs styles*/

.hljs {
	display: block;
	overflow-x: auto;
	padding: .5em;
	background: #1d1f21
}

.hljs,
.hljs-subst {
	color: #c5c8c6
}

.hljs-comment {
	color: #888
}

.hljs-attribute,
.hljs-doctag,
.hljs-keyword,
.hljs-meta-keyword,
.hljs-name,
.hljs-selector-tag {
    font-weight: 700;
    color: #81a2be;
}

.hljs-deletion,
.hljs-number,
.hljs-quote,
.hljs-selector-class,
.hljs-selector-id,
.hljs-string,
.hljs-template-tag,
.hljs-type {
	color: #99cc99;
}

.hljs-section,
.hljs-title {
	color: #99cc99;
	font-weight: 700
}

.hljs-link,
.hljs-regexp,
.hljs-selector-attr,
.hljs-selector-pseudo,
.hljs-symbol,
.hljs-template-variable,
.hljs-variable {
	color: #bc6060
}

.hljs-literal {
	color: #78a960
}

.hljs-addition,
.hljs-built_in,
.hljs-bullet,
.hljs-code {
	color: #de935f;
}

.hljs-meta {
	color: #1f7199
}

.hljs-meta-string {
	color: #4d99bf
}

.hljs-emphasis {
	font-style: italic
}

.hljs-strong {
	font-weight: 700
}
 
    
,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: