Reference · Mermaid 11
Mermaid cheat sheet: every diagram type's syntax on one page
In short
Mermaid renders diagrams from text. Each diagram starts with its keyword on the first line — flowchart, sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, gantt, pie, timeline, mindmap, gitGraph, quadrantChart, journey, xychart-beta, block-beta — followed by the statements in that type's grammar. This page gives one minimal valid snippet and one syntax table per type, the errors that catch everyone, and the %%{init}%% / frontmatter config keys. Verified against the Mermaid 11 documentation.
Updated · by the ChartCraft team
Which Mermaid diagram types exist?
Fourteen that are stable in Mermaid 11, each with its own first-line keyword. Flowchart, sequence, class, state and ER cover software design; gantt, timeline, journey, quadrant, pie and xychart cover planning and data; mindmap, gitGraph and block cover the rest.
| Diagram | First line | Use it for | ChartCraft equivalent |
|---|---|---|---|
| Flowchart | flowchart LR | Processes, algorithms, decision trees | Flowchart generator |
| Sequence | sequenceDiagram | Messages between participants over time | Sequence diagram generator |
| Class | classDiagram | UML classes and relationships | Class diagram generator |
| State | stateDiagram-v2 | Lifecycles, finite-state machines | State diagram generator |
| Entity relationship | erDiagram | Database schemas, crow's foot cardinality | ER diagram generator |
| Gantt | gantt | Schedules with dates and dependencies | — |
| Pie | pie | Share of a whole | — |
| Timeline | timeline | Events by period | Timeline syntax reference |
| Mindmap | mindmap | Hierarchical brainstorms | — |
| Git graph | gitGraph | Branch and merge history | — |
| Quadrant chart | quadrantChart | 2×2 prioritisation | — |
| User journey | journey | Steps with a 1–5 mood score per actor | — |
| XY chart | xychart-beta | Bar and line charts | — |
| Block diagram | block-beta | Grid-placed boxes, architecture sketches | Architecture diagram generator |
What is the syntax for each Mermaid diagram type?
One minimal snippet and one table per type. Every snippet below is complete and parses as written; copy it, then extend it with the rows from its table.
Flowchart — flowchart TD | LR | BT | RL
Nodes are declared by id plus a shape bracket; links are the arrow operators. graph is the older synonym for flowchart.
flowchart LR
A[Start] --> B{Valid?}
B -- yes --> C([Done])
B -- no --> D[Fix it]
D --> B
Node shapes
flowchart TD
A[Rectangle]
B(Rounded)
C([Stadium])
D[[Subroutine]]
E[(Database)]
F((Circle))
G>Flag]
H{Decision}
I{{Hexagon}}
J[/Parallelogram/]
K[/Trapezoid\]
L(((Double circle)))
M@{ shape: doc, label: "Document (v11.3+)" }| Syntax | Shape |
|---|---|
A[text] | Rectangle (process) |
A(text) | Rounded rectangle |
A([text]) | Stadium (terminator) |
A[[text]] | Subroutine |
A[(text)] | Cylinder (database) |
A((text)) | Circle |
A>text] | Asymmetric flag |
A{text} | Rhombus (decision) |
A{{text}} | Hexagon (preparation) |
A[/text/] | Parallelogram (input/output) |
A[\text\] | Parallelogram, reversed |
A[/text\] | Trapezoid |
A[\text/] | Trapezoid, reversed |
A(((text))) | Double circle |
A@{ shape: doc } | v11.3+ shape syntax; names include rect, rounded, stadium, subproc, cyl, circle, diam, hex, lean-r, lean-l, trap-b, trap-t, dbl-circ, doc, docs, cross-circ, delay, h-cyl, lin-cyl, odd, comment, fork, hourglass, tag-rect, flag |
Arrow and link types
| Syntax | Meaning | Example |
|---|---|---|
--> | Arrow | A --> B |
--- | Open link (no head) | A --- B |
-.-> | Dotted arrow | A -.-> B |
==> | Thick arrow | A ==> B |
~~~ | Invisible link (layout only) | A ~~~ B |
--o | Circle end | A --o B |
--x | Cross end | A --x B |
<--> | Bidirectional | A <--> B |
-- text --> | Arrow with label | A -- yes --> B |
-->|text| | Arrow with label (short form) | A -->|yes| B |
-.text.-> | Dotted with label | A -. maybe .-> B |
----> | Longer link (extra dash = one more rank) | A ----> B |
& | Fan-out / fan-in | A --> B & C |
e1@--> | Edge with an id (v11.1+), for later styling or animation | A e1@--> B |
Subgraphs, direction and styling
flowchart LR
subgraph api [API tier]
direction TB
A[Gateway] --> B[Service]
end
B --> C[(DB)]| Syntax | Meaning |
|---|---|
subgraph id [Title] … end | Group nodes; the id is optional |
direction TB | Direction inside a subgraph (ignored if a node links outside) |
classDef hot fill:#fdd,stroke:#c00 | Define a style class |
class A,B hot or A:::hot | Apply it |
style A fill:#eee | Inline style for one node |
linkStyle 0 stroke:#c00 | Style the n-th link |
click A "https://…" _blank | Hyperlink (securityLevel loose for callbacks) |
%% comment | Comment |
Sequence diagram — sequenceDiagram
Participants appear in declaration order; each message is A arrow B: text. Fragments (alt, loop, par…) close with end.
sequenceDiagram
autonumber
actor U as User
participant S as Server
U->>+S: POST /login
alt valid
S-->>-U: 200 OK
else invalid
S-->>U: 401
end
Note over U,S: session starts
Message arrows
| Syntax | Meaning |
|---|---|
A->B: msg | Solid line, no head |
A-->B: msg | Dashed line, no head |
A->>B: msg | Solid line, arrowhead (synchronous call) |
A-->>B: msg | Dashed line, arrowhead (reply) |
A<<->>B: msg | Solid, arrowheads both ends (v11+) |
A<<-->>B: msg | Dashed, arrowheads both ends (v11+) |
A-xB: msg | Solid line, cross at the end (lost message) |
A--xB: msg | Dashed line, cross at the end |
A-)B: msg | Solid line, open arrow (asynchronous) |
A--)B: msg | Dashed line, open arrow (asynchronous) |
Participants, notes and fragments
| Syntax | Meaning |
|---|---|
participant A as Alice | Declare and alias a lifeline (order of declaration = left-to-right order) |
actor A | Stick-figure lifeline |
create participant X / destroy X | Create and destroy lifelines mid-flow (v10.3+) |
activate A / deactivate A or ->>+ / -->>- | Activation bars |
Note right of A: text / Note over A,B: text | Notes |
loop label … end | Repetition |
alt cond … else … end | Alternatives |
opt cond … end | Optional block |
par … and … end | Parallel |
critical … option … end | Critical region |
break cond … end | Break out of the enclosing flow |
rect rgb(240,240,240) … end | Background highlight |
box Name … end | Group participants |
autonumber | Number every message |
%% comment | Comment line |
Class diagram — classDiagram
Classes are declared with class Name { members } or implicitly by a relationship. Visibility prefixes and the relationship operators follow UML; see the UML diagram types reference for what each arrow means.
classDiagram
direction LR
class Animal {
<<abstract>>
+String name
+speak() String
}
class Dog
Animal <|-- Dog
Owner "1" o-- "*" Dog : keeps
Dog ..> Food : eats
note for Dog "Barks"
Relationships
| Syntax | Meaning |
|---|---|
A <|-- B | Inheritance (generalization) |
A *-- B | Composition |
A o-- B | Aggregation |
A --> B | Association (directed) |
A -- B | Link (solid, undirected) |
A ..> B | Dependency |
A ..|> B | Realization |
A .. B | Link (dashed) |
A "1" --> "*" B | Multiplicity on each end: 1, 0..1, *, 1..*, n, 0..n |
A : label B | Relationship label after the target |
Members and annotations
| Syntax | Meaning |
|---|---|
+name | Public |
-name | Private |
#name | Protected |
~name | Package / internal |
+run() void | Operation; return type after the parentheses |
+count$ | Static member ($ suffix) |
+area()* | Abstract operation (* suffix) |
List~int~ items | Generic type (~ instead of < >) |
<<interface>> | Annotation inside the class body, also <<abstract>>, <<enumeration>>, <<service>> |
note for ClassName "text" | Note attached to a class |
State diagram — stateDiagram-v2
[*] is both the initial and the final pseudostate depending on which side of the arrow it sits. Composite states nest with braces.
stateDiagram-v2
direction LR
[*] --> Idle
Idle --> Running : start
state Running {
[*] --> Fast
Fast --> Slow
}
Running --> Idle : stop
Running --> [*] : fail
note right of Idle : waits for input
| Syntax | Meaning |
|---|---|
[*] --> S | Initial pseudostate |
S --> [*] | Final state |
A --> B : event | Transition with label |
state "Long name" as S1 | State with a display name |
state S { … } | Composite state (nested) |
-- | Concurrent regions inside a composite state |
state c <<choice>> | Choice pseudostate |
state f <<fork>> / <<join>> | Fork / join |
note right of S : text | Note (left of / right of) |
direction LR | Layout direction (TB default) |
classDef / class S cls | Style states (v10.7+) |
Entity relationship diagram — erDiagram
Each relationship line is ENTITY cardinality--cardinality ENTITY : label. The cardinality marks are crow's foot: the symbol nearest each entity describes that entity's side. Full notation on ER diagram symbols.
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE_ITEM : contains
CUSTOMER {
int id PK
string email UK "login"
}
ORDER {
int id PK
int customer_id FK
}
Crow's foot codes
| Code | Meaning |
|---|---|
|| | Exactly one |
|o | Zero or one |
}| | One or more |
}o | Zero or more |
A ||--o{ B : label | Identifying relationship (solid line); one A, zero-or-many B |
A ||..o{ B : label | Non-identifying relationship (dashed line) |
A {
type name PK
} | Attribute block: type, name, then PK / FK / UK, then an optional "comment" |
A["Display name"] | Alias for an entity (v10.5+) |
| Left (near first entity) | Right (near second entity) | Reads as |
|---|---|---|
|| | || | one to one |
|| | o{ | one to zero-or-many |
|| | |{ | one to one-or-many |
|o | o| | zero-or-one to zero-or-one |
}o | o{ | many to many |
Gantt chart — gantt
Set dateFormat first; every task is name : tags, id, start, end-or-duration. Tasks can start after another task's id.
gantt
title Release plan
dateFormat YYYY-MM-DD
axisFormat %b %d
excludes weekends
section Build
Design :done, d1, 2026-10-01, 5d
Develop :active, d2, after d1, 10d
section Ship
QA :crit, q1, after d2, 4d
Launch :milestone, m1, after q1, 0d
| Syntax | Meaning |
|---|---|
dateFormat YYYY-MM-DD | Input date format (day.js tokens) |
axisFormat %m-%d | Axis label format (d3-time tokens) |
tickInterval 1week | Axis tick spacing |
excludes weekends | Skip days: weekends, or a date list, or a weekday name |
section Name | Row group |
Task :id, start, end|duration | Task; start can be a date or `after otherId`; duration like 3d, 2w, 12h |
Task :done, … / :active, … / :crit, … | Status tags before the id |
Task :milestone, id, date, 0d | Milestone (zero duration) |
todayMarker off | Hide the today line |
Pie chart — pie
Labels in double quotes, a colon, then a positive number; slices are drawn clockwise in the order given. showData prints the values in the legend.
pie showData
title Traffic by source
"Organic" : 62
"Direct" : 23
"Referral" : 15
| Syntax | Meaning |
|---|---|
pie showData | Show values next to labels |
title Text | Chart title |
"Label" : 42 | One slice; numbers may be decimal |
Timeline — timeline
Periods are lines; events follow a colon and several events can share one period. Sections group periods. The complete reference, with styling and errors, is on Mermaid timeline syntaxChen notation for ER diagramsCrow's foot notationUML diagram typesMermaid cheat sheetData flow diagram symbolsBPMN symbolsClass diagram symbolsActivity diagram symbols.
timeline
title History of Mermaid
section Early
2014 : First release
section Growth
2022 : v9 : timeline added
2024 : v11
| Syntax | Meaning |
|---|---|
title Text | Title |
section Name | Group of periods (coloured band) |
2024 : Event | Period with one event |
2024 : Event A : Event B | Several events in one period |
%% comment | Comment |
Mindmap — mindmap
Hierarchy comes from indentation alone. The root may take a shape; children may too. Icons and classes attach to the preceding node.
mindmap
root((Launch))
Marketing
Blog post
::icon(fa fa-pen)
Newsletter
Product
[Changelog]
((Demo))
| Syntax | Meaning |
|---|---|
root((text)) | Root as a circle (any shape works) |
id[text] | Square |
id(text) | Rounded square |
id((text)) | Circle |
id))text(( | Bang |
id)text( | Cloud |
id{{text}} | Hexagon |
::icon(fa fa-book) | Icon on the previous node (icon font must be loaded by the host) |
:::class1 class2 | CSS classes on the previous node |
Git graph — gitGraph
Statements run in order like git commands on a current branch. main exists implicitly; orientation is set with gitGraph LR:, TB: or BT: (v11+).
gitGraph
commit id: "init"
branch develop
checkout develop
commit id: "feature"
checkout main
merge develop tag: "v1.0"
commit type: HIGHLIGHT
| Syntax | Meaning |
|---|---|
commit | Commit on the current branch |
commit id: "x" tag: "v1" type: HIGHLIGHT | Commit with id, tag and type (NORMAL, REVERSE, HIGHLIGHT) |
branch name | Create and switch to a branch (order: 2 to control lane position) |
checkout name / switch name | Switch branch (interchangeable) |
merge name | Merge into the current branch; accepts id, tag, type |
cherry-pick id: "x" | Cherry-pick an existing commit from another branch |
Quadrant chart — quadrantChart
Both axes run 0 → 1. Quadrants are numbered counter-clockwise from the top right: 1 top-right, 2 top-left, 3 bottom-left, 4 bottom-right.
quadrantChart
title Effort vs impact
x-axis Low effort --> High effort
y-axis Low impact --> High impact
quadrant-1 Plan carefully
quadrant-2 Do first
quadrant-3 Skip
quadrant-4 Maybe later
Cheat sheet: [0.25, 0.8]
Rewrite: [0.85, 0.7]
| Syntax | Meaning |
|---|---|
x-axis Left --> Right | X labels (right label optional) |
y-axis Bottom --> Top | Y labels |
quadrant-1 Text | Quadrant labels 1–4 |
Name: [0.3, 0.6] | A point; both values 0–1 |
Name:::class: [x, y] | Point with a class (v11+) |
User journey — journey
Each task is name: score: actors; the score is 1 (worst) to 5 (best) and draws the face. Actors are comma-separated and get a colour each.
journey
title Buy a ticket
section Search
Open app: 5: Rider
Find route: 3: Rider
section Pay
Enter card: 2: Rider
Confirm: 4: Rider, System
| Syntax | Meaning |
|---|---|
title Text | Title |
section Name | Phase of the journey |
Task name: 3: Me | Task with score and one actor |
Task name: 5: Me, Cat | Several actors |
XY chart — xychart-beta
Bar and line series share the axes. The x-axis is a category list or a numeric range; the y-axis is a numeric range or auto. Newer releases also accept the keyword xychart; xychart-beta works everywhere Mermaid 10.6+ runs.
xychart-beta
title "Signups per month"
x-axis [Jan, Feb, Mar, Apr]
y-axis "Signups" 0 --> 400
bar [120, 180, 260, 340]
line [120, 180, 260, 340]
| Syntax | Meaning |
|---|---|
xychart-beta horizontal | Horizontal bars (vertical is default) |
title "Text" | Title (quote if it has spaces) |
x-axis [a, b, "c d"] | Categorical x-axis |
x-axis "Label" 0 --> 100 | Numeric x-axis |
y-axis "Label" min --> max | Numeric y-axis (omit the range for auto) |
bar [1, 2, 3] | Bar series |
line [1, 2, 3] | Line series |
Block diagram — block-beta
Blocks fill a grid left to right; columns sets the width, space leaves a cell empty, block:id … end nests a grid, and flowchart-style shapes and arrows apply. Newer releases also accept the keyword block.
block-beta
columns 3
Client space DB[("Database")]
block:api:3
columns 2
Gateway Service
end
Client --> Gateway
Service --> DB
| Syntax | Meaning |
|---|---|
columns 3 | Number of grid columns |
a["Label"] | Block with a label; flowchart shapes work ((x)), [(x)], {x} … |
a:2 | Block spanning two columns |
space / space:2 | Empty cell(s) |
block:id:2 … end | Nested block spanning two columns, with its own columns |
a --> b | Edge (needs both blocks declared; -- "text" --> for a label) |
id<["Label"]>(right) | Block arrow shape: right, left, up, down, x, y |
style a fill:#eef,stroke:#333 | Style one block |
How do I set the theme and config in Mermaid?
Two ways: a YAML frontmatter block above the diagram (preferred since v10.5) or an %%{init: …}%% directive on the first line. Both override the site defaults set by mermaid.initialize(); frontmatter wins when both are present.
---
title: Checkout
config:
theme: forest
look: handDrawn
layout: elk
---
flowchart LR
A --> B%%{init: {'theme': 'dark', 'flowchart': {'curve': 'linear'}}}%%
flowchart LR
A --> B| Key / syntax | Meaning |
|---|---|
%%{init: {'theme': 'dark'}}%% | Directive on the first line; keys use single quotes inside %%{ }%%. Deprecated in favour of frontmatter but still supported. |
---
config:
theme: forest
--- | YAML frontmatter (v10.5+), the preferred form; goes before the diagram keyword |
theme | default · neutral · dark · forest · base (base is the one to customise with themeVariables); v11.11+ adds neo, neo-dark, redux, redux-dark |
themeVariables | primaryColor, primaryTextColor, primaryBorderColor, lineColor, secondaryColor, tertiaryColor, fontFamily, fontSize … |
look: handDrawn | Sketchy rendering (v11+); classic is the default |
layout: elk | Use the ELK layout engine for flowchart / state / class (v11+; needs the @mermaid-js/layout-elk package or mermaid.live) |
title: My diagram | Frontmatter title (rendered above the diagram for most types) |
flowchart: { curve: linear | basis | step … , htmlLabels: false } | Edge curve style, label rendering |
sequence: { mirrorActors: false, showSequenceNumbers: true } | Sequence options |
gantt: { barHeight: 20, fontSize: 11 } | Gantt sizing |
securityLevel: strict | loose | antiscript | Site-level only (mermaid.initialize); loose enables click callbacks and HTML labels |
What are the most common Mermaid errors and how do I fix them?
Nearly every parse error is one of: a wrong or misspelled keyword on line one, a reserved word used as a node id, an unquoted special character in a label, or a host that bundles an older Mermaid than the syntax you used.
| Symptom | Cause → fix |
|---|---|
| Parse error on line 1 / "No diagram type detected" | First line is not a diagram keyword, or has leading characters. Keywords are case-sensitive: flowchart, sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, gantt, pie, timeline, mindmap, gitGraph, quadrantChart, journey, xychart-beta, block-beta. |
| Flowchart breaks after a node called end | Lowercase end is reserved (closes a subgraph). Use End, END or quote it: e["end"]. |
| A---oB or A---xB draws a circle or cross you did not want | A node id starting with o or x after a link is read as an edge decoration. Add a space (A--- oB) or capitalise (A---Ops). |
| Parentheses, brackets or quotes inside a label break the parser | Wrap the label in double quotes: A["f(x) = [1, 2]"]. For a literal quote use the entity code #quot;. Numeric entities use #35; for #, #59; for ;. |
| Sequence message text with a colon is cut | Only the first colon separates target and text; use #58; for a literal colon in the message. |
| stateDiagram renders differently or fails | Use stateDiagram-v2; the v1 keyword stateDiagram is the legacy renderer and lacks composites, notes and direction. |
| ER attribute names rejected | Entity names use letters, digits and underscores; attribute lines must be type then name; key words PK, FK, UK come after the name, comment last in quotes. |
| Gantt dates ignored or tasks pile up | dateFormat must match the dates you write (2026-10-01 → YYYY-MM-DD). after x needs an id that was declared earlier. |
| Mindmap nodes attach to the wrong parent | Hierarchy is indentation relative to the previous lines; mixed tabs and spaces break it. Use spaces only. |
| Everything renders but the layout is ugly | Change direction (TB / LR), add subgraph direction, use invisible links (~~~) to pull nodes together, or switch layout: elk in the frontmatter (v11+). |
| Diagram works on mermaid.live but not in my wiki / README | The host bundles an older Mermaid. GitHub, GitLab, Notion, Obsidian and Confluence each pin their own version; newer syntax (v11.3 shapes, xychart, block) may not be available. |
When is Mermaid the wrong tool?
When the diagram outgrows the syntax: thirty-plus nodes, swimlanes with cross-lane edges, BPMN, architecture diagrams with tiers, or anyone who needs to edit it without learning the grammar. Mermaid is excellent in READMEs and wikis and painful as a drawing tool.
ChartCraft takes the other route: you describe the diagram in a sentence and it lays it out (ELK layout, orthogonal routing, swimlanes, BPMN, ER with crow's foot, C4-style architecture). The Mermaid alternative page compares the two honestly; the AI diagram generator is the place to try it. For Mermaid syntax that is not on this page — the full timeline grammar, for instance — see Mermaid timeline syntaxChen notation for ER diagramsCrow's foot notationUML diagram typesMermaid cheat sheetData flow diagram symbolsBPMN symbolsClass diagram symbolsActivity diagram symbols.
Frequently asked questions
What is Mermaid?
Mermaid is an open-source JavaScript library (mermaid.js.org) that renders diagrams from a Markdown-like text syntax. It is built into GitHub, GitLab, Notion, Obsidian, Confluence, Azure DevOps and many static-site generators, which is why its syntax is worth knowing even if you use another tool to draw.
Which keyword starts each Mermaid diagram?
flowchart (or graph), sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, gantt, pie, timeline, mindmap, gitGraph, quadrantChart, journey, xychart-beta, block-beta. Keywords are case-sensitive and must be the first non-comment line.
What is the difference between graph and flowchart in Mermaid?
They produce the same diagram. flowchart is the newer keyword and is required for some newer features (subgraph direction, the v11.3 shape syntax); graph is kept for backward compatibility. Use flowchart.
How do I add a label to a Mermaid arrow?
In a flowchart: A -- text --> B or A -->|text| B. In a sequence diagram the text comes after the colon: A->>B: text. In a class or ER diagram the label follows the relationship: A --> B : label.
How do I change the Mermaid theme?
Put a frontmatter block above the diagram: --- config: theme: dark --- (one key per line), or use the directive %%{init: {'theme': 'dark'}}%% on the first line. Built-in themes are default, neutral, dark, forest and base; base is the one designed to be customised with themeVariables.
Why does my Mermaid diagram render on mermaid.live but not on GitHub?
GitHub, GitLab, Notion and other hosts bundle a specific Mermaid version and update it on their own schedule. Features marked v11.x in this cheat sheet (the @{ shape } syntax, xychart, block, handDrawn look, ELK layout) may not be available there yet. Check the host's documentation for its Mermaid version.
Can I use Mermaid for architecture or BPMN diagrams?
Partly. Flowcharts with subgraphs and block diagrams can sketch an architecture, and there is an architecture-beta type for cloud icons, but there is no BPMN, no swimlane engine and limited control over layout. For those, describe the diagram to ChartCraft's architecture diagram generator or BPMN diagram tool instead.
How do I write a comment in Mermaid?
Start the line with %% (two percent signs). Comments must be on their own line. Note that %%{ … }%% is not a comment but a configuration directive.