× Search About Posts Code Music Links
Blank Try
experiment
lots
learn
more

Mermaid JS

Last site update: 8 May 2024

Unfinished article

What is it?

Mermaid JS is a Javascript library that allows diagrams to be added easily to web pages with some simple code. Because it’s so capable there is actually a lot of code to learn but like most languages since you probably won’t use most of it you just learn what you need which typically might just be flow charts. Pie charts are useful too.

Installing

So MermaidJS works by taking specially formatted code inside a <div> tag with a class of mermaid. This code is interpreted by Mermaid JS which creates the diagram.

To install you simply add the code to your site using a CDN or downloading the JS file to your site. You add an initialisation script too:

1{{ with .Params.mermaid }}
2    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
3    <script>
4        mermaid.initialize({ startOnLoad: true });
5    </script>
6{{ end }}

To create a flow chart or other Mermaid diagram you just add your Mermaid code inside of a div tag like so:

So here we go:

1<div class="mermaid">
2  flowchart LR
3    a --> b
4</div>

Et voila. Here is a Mermaid diagram using a Hugo shortcode to add the <div> tag:

1{{⪡ html class="mermaid" ⪢}}
2  flowchart LR
3    a --> b
4{{⪡ /html ⪢}}
flowchart LR a --> b

Use without shortcodes

It’s possible to use Mermaid with code fences (backticks) directly in a Markdown file with the addition of a small amount of Javascript to the <script> tag above.

1window.onload = function() {
2    mermaid.init(undefined, ".language-mermaid");
3};

Here is a simple version of the output. I could (might) change the CSS for code.language-mermaid too if I feel the need to get rid coloured background or do something else like left aligning or whatever.

flowchart LR
a --> b

The slightly weird thing is that the chart appears to be coloured by the syntax highlighting.

A Pie chart

Here’s a pie chart using code fences (backticks):

pie
title My big pie chart
  "pastry" : 1
  "filling": 2

And with a short code:

pie title My big pie chart "pastry" : 1 "filling": 2

NB. By default Mermaid will align the diagram in the center of the parent element (in this case a <div> tag). To change this to left aligned I tried using display: inline-block to div.mermaid. However this cut off the legend of the chart.