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.

DiagramFirst lineUse it forChartCraft equivalent
Flowchartflowchart LRProcesses, algorithms, decision treesFlowchart generator
SequencesequenceDiagramMessages between participants over timeSequence diagram generator
ClassclassDiagramUML classes and relationshipsClass diagram generator
StatestateDiagram-v2Lifecycles, finite-state machinesState diagram generator
Entity relationshiperDiagramDatabase schemas, crow's foot cardinalityER diagram generator
GanttganttSchedules with dates and dependencies—
PiepieShare of a whole—
TimelinetimelineEvents by periodTimeline syntax reference
MindmapmindmapHierarchical brainstorms—
Git graphgitGraphBranch and merge history—
Quadrant chartquadrantChart2×2 prioritisation—
User journeyjourneySteps with a 1–5 mood score per actor—
XY chartxychart-betaBar and line charts—
Block diagramblock-betaGrid-placed boxes, architecture sketchesArchitecture 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+)" }
SyntaxShape
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

SyntaxMeaningExample
-->ArrowA --> B
---Open link (no head)A --- B
-.->Dotted arrowA -.-> B
==>Thick arrowA ==> B
~~~Invisible link (layout only)A ~~~ B
--oCircle endA --o B
--xCross endA --x B
<-->BidirectionalA <--> B
-- text -->Arrow with labelA -- yes --> B
-->|text|Arrow with label (short form)A -->|yes| B
-.text.->Dotted with labelA -. maybe .-> B
---->Longer link (extra dash = one more rank)A ----> B
& Fan-out / fan-inA --> B & C
e1@-->Edge with an id (v11.1+), for later styling or animationA e1@--> B

Subgraphs, direction and styling

flowchart LR
  subgraph api [API tier]
    direction TB
    A[Gateway] --> B[Service]
  end
  B --> C[(DB)]
SyntaxMeaning
subgraph id [Title] … endGroup nodes; the id is optional
direction TBDirection inside a subgraph (ignored if a node links outside)
classDef hot fill:#fdd,stroke:#c00Define a style class
class A,B hot or A:::hotApply it
style A fill:#eeeInline style for one node
linkStyle 0 stroke:#c00Style the n-th link
click A "https://…" _blankHyperlink (securityLevel loose for callbacks)
%% commentComment

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

SyntaxMeaning
A->B: msgSolid line, no head
A-->B: msgDashed line, no head
A->>B: msgSolid line, arrowhead (synchronous call)
A-->>B: msgDashed line, arrowhead (reply)
A<<->>B: msgSolid, arrowheads both ends (v11+)
A<<-->>B: msgDashed, arrowheads both ends (v11+)
A-xB: msgSolid line, cross at the end (lost message)
A--xB: msgDashed line, cross at the end
A-)B: msgSolid line, open arrow (asynchronous)
A--)B: msgDashed line, open arrow (asynchronous)

Participants, notes and fragments

SyntaxMeaning
participant A as AliceDeclare and alias a lifeline (order of declaration = left-to-right order)
actor AStick-figure lifeline
create participant X / destroy XCreate and destroy lifelines mid-flow (v10.3+)
activate A / deactivate A or ->>+ / -->>-Activation bars
Note right of A: text / Note over A,B: textNotes
loop label … endRepetition
alt cond … else … endAlternatives
opt cond … endOptional block
par … and … endParallel
critical … option … endCritical region
break cond … endBreak out of the enclosing flow
rect rgb(240,240,240) … endBackground highlight
box Name … endGroup participants
autonumberNumber every message
%% commentComment 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

SyntaxMeaning
A <|-- BInheritance (generalization)
A *-- BComposition
A o-- BAggregation
A --> BAssociation (directed)
A -- BLink (solid, undirected)
A ..> BDependency
A ..|> BRealization
A .. BLink (dashed)
A "1" --> "*" BMultiplicity on each end: 1, 0..1, *, 1..*, n, 0..n
A : label BRelationship label after the target

Members and annotations

SyntaxMeaning
+namePublic
-namePrivate
#nameProtected
~namePackage / internal
+run() voidOperation; return type after the parentheses
+count$Static member ($ suffix)
+area()*Abstract operation (* suffix)
List~int~ itemsGeneric 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
SyntaxMeaning
[*] --> SInitial pseudostate
S --> [*]Final state
A --> B : eventTransition with label
state "Long name" as S1State 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 : textNote (left of / right of)
direction LRLayout direction (TB default)
classDef / class S clsStyle 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

CodeMeaning
||Exactly one
|oZero or one
}|One or more
}oZero or more
A ||--o{ B : labelIdentifying relationship (solid line); one A, zero-or-many B
A ||..o{ B : labelNon-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
|oo|zero-or-one to zero-or-one
}oo{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
SyntaxMeaning
dateFormat YYYY-MM-DDInput date format (day.js tokens)
axisFormat %m-%dAxis label format (d3-time tokens)
tickInterval 1weekAxis tick spacing
excludes weekendsSkip days: weekends, or a date list, or a weekday name
section NameRow group
Task :id, start, end|durationTask; 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, 0dMilestone (zero duration)
todayMarker offHide 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
SyntaxMeaning
pie showDataShow values next to labels
title TextChart title
"Label" : 42One 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
SyntaxMeaning
title TextTitle
section NameGroup of periods (coloured band)
2024 : EventPeriod with one event
2024 : Event A : Event BSeveral events in one period
%% commentComment

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))
SyntaxMeaning
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 class2CSS 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
SyntaxMeaning
commitCommit on the current branch
commit id: "x" tag: "v1" type: HIGHLIGHTCommit with id, tag and type (NORMAL, REVERSE, HIGHLIGHT)
branch nameCreate and switch to a branch (order: 2 to control lane position)
checkout name / switch nameSwitch branch (interchangeable)
merge nameMerge 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]
SyntaxMeaning
x-axis Left --> RightX labels (right label optional)
y-axis Bottom --> TopY labels
quadrant-1 TextQuadrant 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
SyntaxMeaning
title TextTitle
section NamePhase of the journey
Task name: 3: MeTask with score and one actor
Task name: 5: Me, CatSeveral 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]
SyntaxMeaning
xychart-beta horizontalHorizontal 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 --> 100Numeric x-axis
y-axis "Label" min --> maxNumeric 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
SyntaxMeaning
columns 3Number of grid columns
a["Label"]Block with a label; flowchart shapes work ((x)), [(x)], {x} …
a:2Block spanning two columns
space / space:2Empty cell(s)
block:id:2 … endNested block spanning two columns, with its own columns
a --> bEdge (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:#333Style 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 / syntaxMeaning
%%{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
themedefault · neutral · dark · forest · base (base is the one to customise with themeVariables); v11.11+ adds neo, neo-dark, redux, redux-dark
themeVariablesprimaryColor, primaryTextColor, primaryBorderColor, lineColor, secondaryColor, tertiaryColor, fontFamily, fontSize …
look: handDrawnSketchy rendering (v11+); classic is the default
layout: elkUse the ELK layout engine for flowchart / state / class (v11+; needs the @mermaid-js/layout-elk package or mermaid.live)
title: My diagramFrontmatter 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 | antiscriptSite-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.

SymptomCause → 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 endLowercase 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 wantA 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 parserWrap 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 cutOnly the first colon separates target and text; use #58; for a literal colon in the message.
stateDiagram renders differently or failsUse stateDiagram-v2; the v1 keyword stateDiagram is the legacy renderer and lacks composites, notes and direction.
ER attribute names rejectedEntity 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 updateFormat 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 parentHierarchy is indentation relative to the previous lines; mixed tabs and spaces break it. Use spaces only.
Everything renders but the layout is uglyChange 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 / READMEThe 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.

Tired of parse errors? Describe the diagram in a sentence instead.

Skip the syntax: describe the diagram →