Beginner’s Guide to Prism.js: Simple Steps to Beautiful Code Highlighting
This site also uses it, and here we explain how to use Prism.js in a beginner-friendly way.
Prism.js is a lightweight and easy-to-use JavaScript library that provides syntax highlighting for programming code on web pages. Below are the basic steps for using Prism.js.
Download Prism.js
- Visit the official Prism.js website (Prism.js).
- Select the required languages, themes, and plugins.
This time, to display line numbers, we checked “Line Numbers”. - Click the “Download” button to download the customized Prism.js and CSS files.
Include Prism.js in Your HTML File
Include the downloaded prism.js and prism.css files in your HTML file. Typically, you place the CSS file inside the head tag and the JavaScript file near the end of the body tag.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo page showing syntax highlighting for programming code (pre, code tags) on a web page using prism.js</title>
<!-- Include the Prism.js CSS file -->
<link href="prism.css" rel="stylesheet" />
</head>
<body>
<h1>Display syntax highlighting for programming code (pre, code tags) on a web page using prism.js</h1>
<pre class="line-numbers"><code class="language-javascript">// Write your JavaScript code here
console.log("Hello, world!");
</code></pre>
<!-- Include the Prism.js JavaScript file -->
<script src="prism.js"></script>
</body>
</html>
Marking Up Code Blocks
Wrap the code blocks you want to highlight with Prism.js in pre and code tags, and specify the appropriate language class. For example, to highlight JavaScript code, do the following.
<pre class="line-numbers"><code class="language-javascript">// Write your JavaScript code here
console.log("Hello, world!");
</code></pre>
The class=”language-javascript” part of the code tag specifies which language Prism.js should apply syntax highlighting to.
Since we downloaded it with “Line Numbers” checked to display line numbers, adding class=”line-numbers” to the pre tag will display line numbers.
Demo Page: Displaying Syntax Highlighting for Programming Code (pre, code tags) on a Web Page Using prism.js
By opening the demo page below, you can confirm that syntax highlighting is applied to the specified code blocks.
Notes
- File paths:
Make sure the paths to the downloaded prism.js and prism.css files are specified correctly. - Language support:
If you want to use highlighting for a specific language, ensure that the language is included in Prism.js. - HTML escaping:
When writing code directly in HTML, you need to properly escape special characters (such as < and >).
Finally
Now you’ve mastered the basic usage of Prism.js! Use this as a reference and try adding beautiful syntax highlighting to your web pages.
* If you reuse this, please do so at your own responsibility.
Do not reuse the Google Analytics tag in the head tag of the demo page.
