mermaid-syntax
Mermaid Diagram Syntax Guide
Comprehensive syntax reference for generating error-free Mermaid diagrams. Prevents common mistakes and supports Mermaid v11 features including flowcharts, sequence diagrams, class diagrams, state diagrams, ER diagrams, Gantt charts, and more.
Test diagrams at: https://mermaid.live/
Prefer flowchart over graph: Both work, but flowchart is the modern syntax with better feature support.
Critical Rules (Prevent 90% of Errors)
1. Special Character Escaping
Always wrap text containing special characters in double quotes:
flowchart LR
A["Text with (parentheses)"]
B["Text with / or \ slashes"]
C["Colon: in text"]
Characters requiring quotes: ( ) [ ] { } / \ : ; # @ ! ? < > " '
2. Reserved Words (Not Just "end"!)
Multiple reserved words break diagrams. Use quoted labels with safe IDs:
flowchart LR
node1["end"] %% Safe: quoted with different ID
node2["default"] %% Safe: "default" is also reserved
node3["End"] %% Safe: capitalized
All reserved words (use quoted labels):
end,defaultstyle,linkStyle,classDef,classcall,href,click,interpolate
Pattern: safeId["reserved word text"] instead of reserved[text]
3. Node ID Starting Characters
Nodes starting with o or x create unintended edge types:
flowchart LR
orderNode[Order] %% Good: full word
oNode[O-Node] %% Bad: might create circle edge
Solution: Use descriptive IDs, avoid single letters o or x at start.
4. HTML Entity Codes for Semicolons
In sequence diagrams, semicolons define line breaks. Use #59; for literal semicolons:
sequenceDiagram
A->>B: Value#59; Key#59; Data
5. Comments Must Use %%
Single % breaks diagrams. Always use %%:
flowchart LR
%% This is a valid comment
A --> B
6. Subgraph with HTML Tags
Wrap subgraph titles containing <br/> in quotes:
flowchart TB
subgraph "Title with<br/>line break"
A --> B
end
7. Style Property Escaping
Escape commas in stroke-dasharray with backslash:
flowchart LR
A --> B
linkStyle 0 stroke-dasharray: 5\,5
8. Frontmatter Must Be First Line
The --- for frontmatter MUST be the only content on line 1:
---
config:
theme: forest
---
flowchart LR
A --> B
Wrong: Any whitespace or content before --- breaks the diagram.
9. Mindmap < Character Bug
In mindmaps, < renders as <. Use words instead:
mindmap
root((Comparison))
Less than 10 %% Instead of "< 10"
Greater than 5 %% Instead of "> 5"
10. Class Diagram Colon Limitations
Colons in class member types are tricky. Use return type syntax:
classDiagram
class MyClass {
+getData() Map~String, Object~
}
Note: Complex generic types with colons may not render correctly.
11. Nested Subgraph Linking Bug
Linking to both parent AND nested subgraph causes syntax error:
flowchart LR
%% BAD: linking to both system AND sub-system breaks
%% A --> system
%% B --> sub-system
%% GOOD: link to nodes inside, not subgraph itself
A --> service1
B --> service2
subgraph system
subgraph sub-system
service1
service2
end
end
Workaround: Link to nodes inside subgraphs, not the subgraph ID itself.
12. Subgraph Direction Inheritance
If subgraph nodes link to outside, direction is ignored (inherits parent):
flowchart LR
A --> B
subgraph sub [My Subgraph]
direction TB %% Ignored if C links outside!
C --> D
end
B --> C %% This external link forces LR direction
Rule: Subgraph direction only works if all nodes stay internal.
13. v11 Arrowless Edges Bug (v11.0-11.4)
In Mermaid v11.0 to v11.4.x, the --- (line without arrow) syntax is broken and shows arrows:
flowchart LR
%% BROKEN in v11.0-11.4: shows arrow instead of line
A --- B
%% Workaround: use explicit arrow and style
C --> D
linkStyle 0 stroke:#333,stroke-width:2px
Fix: Upgrade to Mermaid v11.5.0 or later.
14. v11 Markdown-by-Default Breaking Change
In v11, ALL node labels render as Markdown by default (breaking change from v10):
flowchart LR
%% v10: plain text, v11: renders as Markdown
A[**bold** and _italic_]
%% Problem: underscores in text become italic
B["file_name_here"] %% Use quotes to prevent issues
Note: Only bold (**) and italic (_ or *) are supported. Inline code with backticks may not work.
15. Configuration Limits (Secure Settings)
maxTextSize (default: 50,000 chars) and maxEdges (default: 500) are secure settings that CANNOT be set via frontmatter:
---
config:
maxTextSize: 100000 %% IGNORED! Secure setting
---
flowchart LR
A --> B
Workaround: These must be set via mermaid.initialize() in JavaScript, not in diagram config.
16. linkStyle Hex Color as Last Attribute Bug
Hex color as the LAST attribute in linkStyle causes parsing error:
flowchart LR
A --> B
%% BAD: hex color as last attribute
%% linkStyle 0 stroke-width:4px,stroke:#FF69B4
%% GOOD: hex color NOT last, or use color name
linkStyle 0 stroke:#FF69B4,stroke-width:4px
%% OR: linkStyle 0 stroke-width:4px,stroke:hotpink
Workaround: Put hex color before other attributes, or use CSS color names.
17. Class Diagram Namespace Limitations
Relationships and notes MUST be defined OUTSIDE namespace blocks:
classDiagram
namespace MyPackage {
class ClassA
class ClassB
}
%% Relationships OUTSIDE namespace block
ClassA --> ClassB
note for ClassA "This note is outside namespace"
Limitation: Nested namespaces not supported. Use flat structure.
18. Architecture Diagram Label Characters
Architecture node labels only support [a-zA-Z0-9_ ]. Hyphens and special chars break:
architecture-beta
%% BAD: service db[Cloud-Name] (hyphen breaks)
%% GOOD: use underscore or spaces
service db(database)[Cloud_Name]
Mermaid v11 New Features
Hand-Drawn Look
%%{init: {"look": "handDrawn"}}%%
flowchart LR
A[Sketchy] --> B[Style]
Bidirectional Arrows (Sequence)
sequenceDiagram
A <<->> B: Bidirectional
A <<-->> B: Bidirectional dotted
Configuration Directive
%%{init: {
"theme": "dark",
"flowchart": {"curve": "linear"}
}}%%
flowchart LR
A --> B
Diagram Type Quick Reference
Flowchart Direction
| Syntax | Direction |
|---|---|
flowchart TB |
Top to Bottom |
flowchart TD |
Top Down (same as TB) |
flowchart BT |
Bottom to Top |
flowchart LR |
Left to Right |
flowchart RL |
Right to Left |
Node Shapes
| Syntax | Shape |
|---|---|
A[text] |
Rectangle |
A(text) |
Rounded rectangle |
A([text]) |
Stadium |
A[[text]] |
Subroutine |
A[(text)] |
Cylinder (database) |
A((text)) |
Circle |
A{text} |
Diamond |
A{{text}} |
Hexagon |
A>text] |
Asymmetric |
Edge Types
| Syntax | Type |
|---|---|
A --> B |
Arrow |
A --- B |
Line (no arrow) |
A -.- B |
Dotted line |
A ==> B |
Thick arrow |
A -.-> B |
Dotted arrow |
A --text--> B |
Arrow with text |
A -- text --- B |
Line with text |
Subgraph Syntax
flowchart TB
subgraph GroupName["Display Title"]
direction LR
A --> B
end
C --> GroupName
Sequence Diagram Essentials
Message Arrow Types
| Syntax | Description |
|---|---|
A->B |
Solid line, no arrow |
A-->B |
Dotted line, no arrow |
A->>B |
Solid line, arrowhead |
A-->>B |
Dotted line, arrowhead |
A-xB |
Solid line, cross end |
A-)B |
Solid line, open arrow (async) |
Participant Definition
sequenceDiagram
participant A as Alice
actor B as Bob
A->>B: Hello
Activation
sequenceDiagram
A->>+B: Request
B-->>-A: Response
Or explicit:
sequenceDiagram
A->>B: Request
activate B
B-->>A: Response
deactivate B
Control Flow
sequenceDiagram
alt Success
A->>B: OK
else Failure
A->>B: Error
end
opt Optional
A->>B: Maybe
end
loop Every minute
A->>B: Ping
end
par Parallel
A->>B: Task1
and
A->>C: Task2
end
Notes
sequenceDiagram
Note right of A: Single line note
Note over A,B: Spanning note
Class Diagram Essentials
Class Definition
classDiagram
class Animal {
+String name
+int age
+makeSound()
}
Visibility Modifiers
| Symbol | Meaning |
|---|---|
+ |
Public |
- |
Private |
# |
Protected |
~ |
Package/Internal |
Relationships
| Syntax | Meaning |
|---|---|
A <|-- B |
Inheritance (B extends A) |
A *-- B |
Composition |
A o-- B |
Aggregation |
A --> B |
Association |
A ..> B |
Dependency |
A ..|> B |
Realization |
Cardinality
classDiagram
Customer "1" --> "*" Order : places
State Diagram Essentials
Basic States
stateDiagram-v2
[*] --> State1
State1 --> State2: transition
State2 --> [*]
Composite States
stateDiagram-v2
state Parent {
[*] --> Child1
Child1 --> Child2
}
Choice and Fork
stateDiagram-v2
state choice <<choice>>
State1 --> choice
choice --> State2: if condition
choice --> State3: else
state fork <<fork>>
State4 --> fork
fork --> State5
fork --> State6
Common Error Patterns
Error 1: Unquoted Special Characters
%% BAD - breaks parsing
A[Click here (optional)]
B[User: Admin]
%% GOOD - quoted text
A["Click here (optional)"]
B["User: Admin"]
Error 2: Reserved Word "end"
%% BAD - breaks diagram
A --> end
subgraph end
%% GOOD - quoted or capitalized
A --> End
A --> ["end"]
subgraph "End Phase"
Error 3: Semicolon in Sequence Diagram
%% BAD - treated as line break
A->>B: key;value;data
%% GOOD - HTML entity
A->>B: key#59;value#59;data
Error 4: Nested Quotes
%% BAD - quote conflict
A["Say "Hello""]
%% GOOD - use single quotes inside
A["Say 'Hello'"]
%% Or use HTML entity
A["Say #quot;Hello#quot;"]
Error 5: Colon Without Quotes in Flowchart
%% BAD - colon breaks node text
A[Step 1: Initialize]
%% GOOD - quoted
A["Step 1: Initialize"]
Other Diagram Types (Quick Start)
ER Diagram
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM : contains
Gantt Chart
gantt
title Project Timeline
dateFormat YYYY-MM-DD
section Phase 1
Task A :a1, 2024-01-01, 30d
Task B :after a1, 20d
Pie Chart
pie title Distribution
"A" : 40
"B" : 30
"C" : 30
Git Graph
gitGraph
commit
branch develop
commit
checkout main
merge develop
Validation Checklist
Before finalizing any Mermaid diagram:
- All text with special characters is quoted
- No reserved words as node IDs (
end,default,style,class, etc.) - No node IDs starting with single
oorx - Semicolons in sequence messages use
#59; - Nested quotes use single quotes or HTML entities
- Subgraph titles are quoted if containing
<br/>or special chars - Diagram type declaration is correct (
flowchart, notflow-chart) - Comments use
%%(not single%) -
stroke-dasharraycommas escaped with\, - Frontmatter
---is on the very first line (no whitespace before) - Mindmaps avoid
<character (use words) - No links to both parent and nested subgraphs (link to nodes inside instead)
- Subgraph direction only reliable if all nodes stay internal
- If using
---(arrowless), verify Mermaid v11.5+ or use workaround - Underscores in labels may render as italic in v11 (use quotes)
-
maxTextSize/maxEdgescan't be set in frontmatter (secure settings) - linkStyle: hex color NOT as last attribute (or use color names)
- classDiagram: relationships and notes OUTSIDE namespace blocks
- architecture-beta: labels use only
[a-zA-Z0-9_ ], no hyphens - Test at https://mermaid.live/ before committing
Additional Resources
Reference Files
For detailed syntax of each diagram type:
references/flowchart-complete.md- All 30+ node shapes, edge styling, subgraph nestingreferences/sequence-complete.md- All message types, boxes, breaks, critical sectionsreferences/class-state-complete.md- Class annotations, state concurrency, ER diagrams, notesreferences/other-diagrams.md- Gantt, Pie, Git Graph, Mindmap, Timeline
Example Files
Working examples in examples/:
examples/flowchart-examples.md- Common flowchart patternsexamples/sequence-examples.md- API flow, auth flow patterns
Scripts
scripts/validate-mermaid.sh- Basic syntax validation helper
External Resources
- Live Editor: https://mermaid.live/ - Test and debug diagrams
- Official Docs: https://mermaid.js.org/intro/syntax-reference.html
- GitHub: https://github.com/mermaid-js/mermaid