I need a good JavaScript library to syntax highlight HTML <pre> element based on language

Home / Blog / I need a good JavaScript library to syntax highlight HTML <pre> element based on language


If you need a CSS library to style HTML `<pre>` code blocks with syntax highlighting based on programming language, the best and most widely used options are:

Prism.js

`Prism.js` is a lightweight, extensible syntax highlighter built with modern web standards. It is specifically designed to highlight code within `<pre><code>` blocks and supports a wide range of programming languages. You assign a language by adding a class like language-javascript or language-python to your `<code>` element. Prism comes with several themes (CSS files) you can use or customize, and it is used on millions of websites.

Example usage:

<link href="themes/prism.css" rel="stylesheet" />
<pre><code class="language-css">p { color: red }</code></pre>
<script src="prism.js"></script>

You can easily extend Prism with plugins and load additional languages as needed. It is also possible to use Prism server-side with Node.js to generate static HTML with highlighted code.

highlight.js

`highlight.js` is another very popular library for syntax highlighting. It can automatically detect the programming language or you can specify it explicitly. Like Prism, it requires you to wrap your code in `<pre><code>` blocks and provides a variety of CSS themes for styling.

Example usage:

<link rel="stylesheet" href="styles/default.css">
<pre><code class="language-python">
def hello():
    print("Hello, world!")
</code></pre>
<script src="highlight.min.js"></script>
<script>hljs.highlightAll();</script>

`highlight.js` supports over 100 languages and is easy to set up via CDN or npm.

Recommendation

For most projects, `Prism.js` or `highlight.js` are the best choices. Both libraries are easy to integrate, highly customizable, and have strong community support. They allow you to style code blocks based on language using CSS themes, and you can easily switch or customize these themes as needed.

Can `hljs.highlightAll()` hook into `<pre>` instead of `<code>` elements?

By default, `hljs.highlightAll()` only highlights code inside `<pre><code>` blocks, because it looks for elements matching the CSS selector 'pre code'. If your code is inside plain `<pre>` tags (without a `<code>` child), `hljs.highlightAll()` will not process them.

To highlight code inside `<pre>` tags only, you can wrap the content of each `<pre>` in a `<code>` tag with JavaScript, then run `hljs.highlightAll()`.

This is a common workaround and works well:

<pre class="language-javascript">
function hello() {
  console.log("Hello, world!");
}
</pre>

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

<script>
  // Find all <pre> tags (optionally with a specific class)
  var preTags = document.getElementsByTagName('pre');
  for (var i = 0; i < preTags.length; i++) {
    // Only wrap if not already wrapped
    if (!preTags[i].querySelector('code')) {
      var code = document.createElement('code');
      code.innerHTML = preTags[i].innerHTML;
      // Copy language class if present
      for (var j = 0; j < preTags[i].classList.length; j++) {
        if (preTags[i].classList[j].startsWith('language-')) {
          code.classList.add(preTags[i].classList[j]);
        }
      }
      preTags[i].innerHTML = '';
      preTags[i].appendChild(code);
    }
  }
  hljs.highlightAll();
</script>

This script wraps each `<pre>`'s content in a `<code>` tag, preserving any language class, and then calls `hljs.highlightAll()`.

How can I make `highlight.js` use `TailwindCSS` styling?

To make `highlight.js` use TailwindCSS stylings, you have several effective options, depending on how tightly you want to integrate `highlight.js` themes with your Tailwind build and whether you want to use existing `highlight.js` themes or fully customize styles with Tailwind utility classes.

Use the `tailwind-highlightjs` Plugin.

The `tailwind-highlightjs` plugin is designed specifically for this purpose. It bakes `highlight.js` themes directly into your `TailwindCSS` build, allowing you to configure, customize, and even extend `highlight.js` styles using your Tailwind setup.

Steps:

Install the plugin:

npm install tailwind-highlightjs

Configure your `tailwind.config.js`:

module.exports = {
  content: ['./src/**/*.html'],
  safelist: [{ pattern: /hljs+/, }],
  plugins: [require('tailwind-highlightjs')],
  theme: {
    hljs: {
      theme: 'night-owl', // or any other official theme name
      // You can also use a custom theme or link to a raw CSS file
    },
  },
};

If you want to further customize, you can extend or override styles in the `theme.hljs.custom` section.

This approach ensures that `highlight.js` classes are included in your Tailwind build and not purged, and you can safely use `highlight.js` with Tailwind utility classes.


Written by X2Y.DEV
Prism.js Highlight.js TailwindCSS Web Dev

0%