If you've ever tried to create a flowchart, sequence diagram, or Gantt chart using plain text, you've probably come across Mermaid. It's a JavaScript-based diagramming tool that lets you write diagrams using a simple markdown-like syntax. But here's the thing without a solid Mermaid diagram code syntax reference nearby, it's easy to forget the exact keywords, formatting rules, and structure each diagram type expects. This reference exists so you spend less time guessing and more time actually building diagrams.
What is Mermaid and why do people use it for diagrams?
Mermaid is an open-source tool that renders diagrams from text-based code. Instead of dragging and dropping shapes in a GUI editor, you write short code snippets that describe your diagram. A parser reads that code and generates an SVG or image output. Developers use it inside documentation tools, wikis, and platforms like GitHub, GitLab, Notion, and Obsidian because it lives alongside your text no switching apps needed.
The syntax follows a declarative approach. You declare what diagram type you want, then list the relationships, nodes, or sequences. This makes it version-control friendly, easy to review in pull requests, and simple to update without rebuilding anything visually. If you've worked with tools like Graphviz for network diagrams, the text-to-diagram concept will feel familiar.
How do you start writing Mermaid diagram code?
Every Mermaid diagram begins with a keyword that declares the diagram type. After that keyword, you define the structure using Mermaid's syntax rules specific to that type. Here's the basic skeleton:
- Diagram type declaration This is the first line. Examples include
graph,sequenceDiagram,classDiagram,stateDiagram-v2,erDiagram,gantt,pie, andflowchart. - Direction or configuration For flowcharts and graphs, you specify direction with
TD(top-down),LR(left-right),BT(bottom-top), orRL(right-left). - Nodes and connections You define elements and link them using arrows (
-->), lines (---), or other connectors depending on the diagram type. - Labels and styling Optional text labels sit on connection lines inside square brackets. Styling can be added with
classDefandstyledirectives.
A minimal flowchart example looks like this: declare flowchart TD, then write A[Start] --> B[End]. That's enough to render a two-node flowchart with an arrow between them.
What are the most common Mermaid diagram types and their syntax?
Flowchart / Graph syntax
Use flowchart TD or graph TD (they behave similarly). Nodes are defined by their ID and shape: square brackets [] for rectangles, parentheses () for rounded rectangles, curly braces {} for diamonds, and double brackets [[]] for subroutines. Connectors include --> for arrows, --- for plain lines, and -.- for dotted lines. Add labels on connectors like A -->|Yes| B.
Sequence diagram syntax
Start with sequenceDiagram. Participants are declared with participant A as Alice or auto-created when first used. Messages flow between participants using A->>B: Hello (solid arrow) or A-->>B: Dashed (dashed arrow). You can add alt/else blocks, loop blocks, note right of A: Some note, and activation boxes with activate/deactivate.
Class diagram syntax
Start with classDiagram. Define classes with class Animal, then add attributes and methods inside curly braces. Relationships use arrows: Animal <|-- Dog for inheritance, Animal o-- Bird for composition, and Animal --> Habitat for association. Multiplicity notation like "1" --> "" is also supported.
Entity-relationship diagram syntax
Use erDiagram to define database schemas. Each entity gets a name followed by attributes in curly braces. Relationships are drawn with connector syntax like PERSON ||--o{ ORDER : places, where the symbols on each side represent cardinality (one, many, zero-or-one, one-or-many). This pairs well with tools for database schema visualization.
Gantt chart syntax
Start with gantt, set a title and date format with dateFormat YYYY-MM-DD, then define sections and tasks. A task looks like Design UI :a1, 2024-01-01, 30d where the label, ID, start date, and duration are specified. Tasks can have states like done, active, or crit for critical path highlighting.
Pie chart syntax
Use pie, then add data lines like "Dogs" : 386 inside a code block. Mermaid calculates percentages automatically and renders a color-coded pie chart. It's simple and doesn't support much customization, but it works well for quick proportional data.
State diagram syntax
Start with stateDiagram-v2. Define states and transitions: s1 --> s2 : Event. You can nest states for composite state machines, mark start states with [], and add notes with note right of s1.
What are the most common mistakes when writing Mermaid syntax?
- Missing the diagram type declaration. Every diagram needs a type keyword as the first line. Without it, nothing renders.
- Using special characters in node labels without quotes. Characters like parentheses, brackets, or pipes inside labels can break parsing. Wrap complex labels in double quotes:
A["Label with (parens)"]. - Forgetting arrow direction.
-->is a single right arrow. Using->or==>incorrectly will cause parse errors. Stick to the documented arrow syntax. - Indentation issues in nested structures. Blocks like
alt/elsein sequence diagrams and nested states require consistent indentation. Mermaid is picky about this. - Confusing
graphandflowchart. Both work for diagrams with nodes and arrows, butflowchartsupports more features like subgraphs and better link labels. Useflowchartfor new work. - Overcomplicating a single diagram. Mermaid works best with moderate complexity. If you have 50+ nodes, consider splitting into multiple diagrams. The rendered output can get hard to read otherwise.
How can you test and preview Mermaid code quickly?
The fastest way is the Mermaid Live Editor. Paste your code on the left panel and see the rendered diagram on the right in real time. It also lets you export SVG, PNG, or a URL to share your diagram with others. This is useful for debugging syntax before committing it to documentation.
For local testing, many code editors have Mermaid preview extensions. VS Code, for example, has several plugins that render Mermaid blocks in markdown preview mode. If you use Obsidian or Notion, both natively support Mermaid code blocks just wrap your code in triple backticks with the mermaid language identifier.
What are some useful syntax tips that most people miss?
- Subgraphs group nodes visually. Use
subgraph Titleandendto wrap related nodes into a labeled box. This keeps complex flowcharts readable. - Click events can add interactivity. In HTML outputs,
click A "https://example.com" "Tooltip"makes a node clickable. This works in some environments that support interactivity. classDefandclassapply reusable styles. Define a style once withclassDef highlight fill:#f96, then apply it withclass A,B highlight. This is much cleaner than inline styling.- Comments use
%%. If you need to leave notes in your code or temporarily disable a line, prefix it with%%. - Theming changes everything. Add
%%{init: {'theme': 'dark'}}%%at the top of your diagram to switch themes. Available themes includedefault,forest,dark, andneutral.
These features make Mermaid more than a basic diagramming tool. If you've used code-driven approaches for diagrams before like generating flowcharts programmatically in Python Mermaid offers a lighter, more portable alternative for documentation-first workflows.
Where does Mermaid work best compared to other diagram tools?
Mermaid shines in environments where diagrams need to live inside documentation, version control, or collaborative platforms. It's not the right choice for pixel-perfect design work or complex architectural blueprints that need fine-grained layout control. Tools like draw.io, Lucidchart, or PlantUML may serve better for those cases. But for embedding clear, maintainable diagrams directly in markdown files, README docs, wikis, and blog posts, Mermaid hits a sweet spot of simplicity and capability.
The official Mermaid.js documentation covers every diagram type in full detail. Bookmark it alongside the live editor, and you'll have everything you need to write and troubleshoot any diagram.
Quick reference checklist for Mermaid diagram syntax
- Start every diagram with the correct type keyword (
flowchart,sequenceDiagram,classDiagram, etc.) - Set direction where applicable (
TD,LR,BT,RL) - Use proper arrow syntax:
-->,---,-.-,==> - Wrap labels with special characters in double quotes
- Use
subgraph/endto group related nodes - Apply
classDefandclassfor reusable styling - Test in the Mermaid Live Editor before committing
- Add
%%{init: {'theme': '...'}}%%for theme customization - Use
%%for comments and debugging - Keep diagrams under ~40 nodes for readability
Keep this checklist next to your editor. The first few times you write Mermaid code, you'll reference it often. After a week of regular use, the syntax becomes second nature and you'll find yourself writing diagrams faster than any drag-and-drop tool allows.
Plantuml for Database Schema Visualization
Graphviz Code Examples for Network Diagrams – Quick Reference Guide
Interactive Uml Diagram Tools for Developers
Generate Flowcharts Directly From Python Code
Uml Diagram Cheat Sheet: Essential Notation Codes for Software Engineers
Mermaid Diagram Syntax Reference Guide for Markup Languages