NW' Blog
July 10, 2026 · Content Page

The Complete Guide to Mermaid Syntax

Mermaid is a JavaScript-based diagramming tool that parses Markdown-like text syntax and renders it as vector diagrams in real time in the browser. This document collects the syntax of all commonly used Mermaid diagram types.


1. Basic Concepts

1.1 Basic Structure

All Mermaid diagrams need to be wrapped in a code block with the language identifier mermaid:

Mermaid
<div class="mermaid-wrapper"><div class="mermaid">
gitGraph LR:
   checkout main
   commit id: "Downtown" tag: "Line 1"
   commit id: "Central Park"
   branch "Line 2 (Blue)"
   commit id: "East Station"
   commit id: "Science Museum"
   checkout main
   commit id: "City Hall (Transfer)" tag: "🔀 Line 1 & 2"
   merge "Line 2 (Blue)"
   commit id: "Financial District"
   branch "Line 3 (Green)"
   commit id: "West Village"
   commit id: "Airport Terminal"
   checkout main
   commit id: "Sports Arena"
   merge "Line 3 (Green)"
   commit id: "Northern Gateway"
   branch "Line 4 (Orange)"
   commit id: "University"
   checkout main
   commit id: "Central Station" tag: "Terminal"
   merge "Line 4 (Orange)"
</div></div>
gitGraph LR: checkout main commit id: "Downtown" tag: "Line 1" commit id: "Central Park" branch "Line 2 (Blue)" commit id: "East Station" commit id: "Science Museum" checkout main commit id: "City Hall (Transfer)" tag: "🔀 Line 1 & 2" merge "Line 2 (Blue)" commit id: "Financial District" branch "Line 3 (Green)" commit id: "West Village" commit id: "Airport Terminal" checkout main commit id: "Sports Arena" merge "Line 3 (Green)" commit id: "Northern Gateway" branch "Line 4 (Orange)" commit id: "University" checkout main commit id: "Central Station" tag: "Terminal" merge "Line 4 (Orange)"

You also need to add the code for the Mermaid component at the end of the file:

Mermaid
<div class="mermaid-wrapper">
  <div class="mermaid">
  graph TD
    A --> B
  </div>
</div>

Mermaid rendering is enabled site-wide (BaseLayout loads mermaid-init.js globally): just write the structure above on any page — no initialization script needed. Diagrams are rendered and the toolbar mounted automatically, both on first load and when navigating to the page via client-side navigation. To customize the theme, you can set a global configuration in the page in advance:

Custom theme (optional)
<script is:inline>
  window.MERMAID_CONFIG = { theme: 'forest' };
</script>

1.2 Comments

Use %% to add comments; comment content is not rendered:

Mermaid
graph TD
            A[Start] --> B{Decision}  %% this is a comment
            B -->|Yes| C[Execute]

2. Flowchart

Flowcharts are the most commonly used diagram type, used to describe processes, algorithms, and decision logic.

2.1 Direction

Direction Syntax Description
Top to bottom TD or TB Most common
Left to right LR Suits processes with many steps
Right to left RL Rarely used
Bottom to top BT Rarely used

2.2 Node Shapes

Shape Syntax Description
Rectangle A[text] Normal step
Rounded rectangle A(text) Start/end
Circle A((text)) Start/end
Diamond A{text} Decision condition
Hexagon A{{text}} Preparation
Parallelogram A[/text/] Input/output
Cylinder A[(text)] Database

2.3 Link Types

Link Syntax Description
With arrow --> Solid arrow
With text `--> text
No arrow --- Solid line without arrow
Thick arrow ==> Thick-line arrow
Dotted arrow -.-> Dotted-line arrow
Dotted with text `-.-> text

2.4 Basic Example

Mermaid
flowchart TD
    A[Start] --> B{Logged in?};
    B -->|Yes| C[Enter homepage]
    B -->|No| D[Redirect to login page]
    C --> E[End]
    D --> E
flowchart TD A[Start] --> B{Logged in?} B -->|Yes| C[Enter homepage] B -->|No| D[Redirect to login page] C --> E[End] D --> E

2.5 Subgraph

Use subgraph to group nodes logically:

Mermaid
flowchart TD
    subgraph User module
        A[User registration] --> B[User login]
    end
    subgraph Business module
        C[Browse products] --> D[Place order and pay]
    end
    B --> C
flowchart TD subgraph User module A[User registration] --> B[User login] end subgraph Business module C[Browse products] --> D[Place order and pay] end B --> C

2.6 Custom Styles

Define style classes with classDef, then apply them with class:

Mermaid
flowchart LR
    A[Start] --> B[Process]
    classDef red fill:#f99,stroke:#333,stroke-width:2px
    class A red 
flowchart LR A[Start] --> B[Process] classDef red fill:#f99,stroke:#333,stroke-width:2px class A red

3. Sequence Diagram

Sequence diagrams show the order of message exchanges between objects.

3.1 Basic Syntax

Mermaid
sequenceDiagram
    participant User
    participant Server
    User->>Server: Send request
    Server-->>User: Return response
sequenceDiagram participant User participant Server User->>Server: Send request Server-->>User: Return response

3.2 Participant Definitions

Define participants with participant; you can use as for aliases:

Mermaid
sequenceDiagram
    participant U as User
    participant S as Server
    U->>S: Request data
sequenceDiagram participant U as User participant S as Server U->>S: Request data

3.3 Message Types

Type Syntax Description
Solid arrow ->> Synchronous message
Dashed arrow -->> Asynchronous response
Solid, no arrow -> Simple message
Dashed, no arrow --> Simple response
Arrow with cross -x Asynchronous message
Arrow with parenthesis -) Asynchronous message

3.4 Activation Boxes

Use + and - to mark activation and deactivation:

Mermaid
sequenceDiagram
    A->>+B: Request
    B-->>-A: Response
sequenceDiagram A->>+B: Request B-->>-A: Response

3.5 Notes

Mermaid
sequenceDiagram
    participant A
    participant B
    Note right of A: This is a note
    Note left of B: Note on the left
    Note over A,B: Note spanning participants
sequenceDiagram participant A participant B Note right of A: This is a note Note left of B: Note on the left Note over A,B: Note spanning participants

3.6 Advanced Structures

Loop (loop):

Mermaid
sequenceDiagram
    loop Run daily
        A->>B: Check status
    end
sequenceDiagram loop Run daily A->>B: Check status end

Conditional (alt/else):

Mermaid
sequenceDiagram
    alt Success
        A->>B: Continue processing
    else Failure
        A->>B: Retry
    end
sequenceDiagram alt Success A->>B: Continue processing else Failure A->>B: Retry end

Parallel (par):

Mermaid
sequenceDiagram
    par Run in parallel
        A->>B: Task 1
    and
        A->>C: Task 2
    end
sequenceDiagram par Run in parallel A->>B: Task 1 and A->>C: Task 2 end

4. Class Diagram

Class diagrams describe the static structure of a system, including classes, attributes, methods, and their relationships.

4.1 Basic Syntax

Mermaid
classDiagram
    class Animal {
        +String name
        -int age
        +void eat()
        -void sleep()
    }
classDiagram class Animal { +String name -int age +void eat() -void sleep() }

4.2 Visibility Markers

Symbol Meaning
+ Public (public)
- Private (private)
# Protected (protected)
~ Package (package)

4.3 Relationship Types

Relationship Syntax Description
Inheritance `< --`
Realization ..|> Interface implementation
Composition *-- Strong ownership
Aggregation o-- Weak ownership
Association --> Plain association

4.4 Complete Example

Mermaid
classDiagram
    Animal <|-- Dog
    Animal <|-- Cat
    Animal : +String name
    Animal : +void move()
    class Dog { 
        +String breed
        +void bark()
    }
classDiagram Animal <|-- Dog Animal <|-- Cat Animal : +String name Animal : +void move() class Dog { +String breed +void bark() }

5. State Diagram

State diagrams describe state machines, lifecycles, and state transitions.

5.1 Basic Syntax

Mermaid
stateDiagram-v2
    [*] --> Pending review
    Pending review --> Approved
    Pending review --> Rejected
    Approved --> [*]
    Rejected --> [*]
stateDiagram-v2 [*] --> Pending review Pending review --> Approved Pending review --> Rejected Approved --> [*] Rejected --> [*]

5.2 States with Descriptions

Mermaid
stateDiagram-v2
    State1: First state
    State2: Second state
    [*] --> State1
    State1 --> State2
stateDiagram-v2 State1: First state State2: Second state [*] --> State1 State1 --> State2

5.3 Composite States

Mermaid
stateDiagram-v2
    [*] --> Running
    state Running { 
        [*] --> Ready
        Ready --> Executing
        Executing --> Ready
    } 
    Running --> [*]
stateDiagram-v2 [*] --> Running state Running { [*] --> Ready Ready --> Executing Executing --> Ready } Running --> [*]

5.4 Fork/Join

Mermaid
stateDiagram-v2
    state fork <<fork>>
    [*] --> fork
    fork --> State A
    fork --> State B
stateDiagram-v2 state fork <<fork>> [*] --> fork fork --> State A fork --> State B

6. Gantt Chart

Gantt charts are used for project schedule management and timeline tracking.

6.1 Basic Syntax

Mermaid
gantt
    title Project development plan
    dateFormat YYYY-MM-DD
    section Requirements phase
        Requirements analysis    :done, a1, 2024-01-01, 7d
        Requirements review    :active, a2, after a1, 3d
    section Development phase
        Frontend development    :a3, after a2, 14d
        Backend development    :a4, after a2, 21d
    section Testing phase
        Integration testing    :a5, after a3, 7d
gantt title Project development plan dateFormat YYYY-MM-DD section Requirements phase Requirements analysis :done, a1, 2024-01-01, 7d Requirements review :active, a2, after a1, 3d section Development phase Frontend development :a3, after a2, 14d Backend development :a4, after a2, 21d section Testing phase Integration testing :a5, after a3, 7d

6.2 Task States

Status Description
done Completed
active In progress
crit Critical path
milestone Milestone

7. Pie Chart

Pie charts show proportions and distributions.

Mermaid
pie title Programming language usage share
    "JavaScript" : 45
    "Python" : 30
    "Java" : 15
    "Go" : 10
pie title Programming language usage share "JavaScript" : 45 "Python" : 30 "Java" : 15 "Go" : 10

Use showData to display the actual values:

Mermaid
pie showData
    title Market share
    "Product A" : 35.5
    "Product B" : 28.3
    "Product C" : 20.2
    "Others" : 16.0
pie showData title Market share "Product A" : 35.5 "Product B" : 28.3 "Product C" : 20.2 "Others" : 16.0

8. Entity Relationship Diagram (ER Diagram)

ER diagrams are used for database relationship modeling.

8.1 Cardinality Notation

Syntax Meaning
`
` o`
}o Zero or more
`} `

8.2 Example

Mermaid
erDiagram
    CUSTOMER ||--o{  ORDER : places
    ORDER ||--|{  LINE_ITEM : contains
    PRODUCT ||--o{  LINE_ITEM : belongs to
    CUSTOMER { 
        int id PK
        string name
        string email
    } 
    ORDER { 
        int id PK
        int customer_id FK
        date created_at
    } 
erDiagram CUSTOMER ||--o{ ORDER : places ORDER ||--|{ LINE_ITEM : contains PRODUCT ||--o{ LINE_ITEM : belongs to CUSTOMER { int id PK string name string email } ORDER { int id PK int customer_id FK date created_at }

9. User Journey

User journey diagrams describe the concrete steps a user takes to complete a task.

Mermaid
journey
    title Shopping experience
    section Browse products
        View product list: 5: User
        Search products: 4: User
    section Place order and pay
        Add to cart: 4: User
        Fill in address: 3: User
        Payment successful: 5: User, System
journey title Shopping experience section Browse products View product list: 5: User Search products: 4: User section Place order and pay Add to cart: 4: User Fill in address: 3: User Payment successful: 5: User, System

The score ranges from 1-5 and indicates satisfaction.

10. Git Branch Diagram (GitGraph)

Git branch diagrams visualize version control branches and commit history.

10.1 Basic Syntax

Mermaid
gitGraph
    commit
    commit
    branch develop
    checkout develop
    commit
    commit
    checkout main
    merge develop
gitGraph commit commit branch develop checkout develop commit commit checkout main merge develop

10.2 Commits with Tags

Mermaid
gitGraph
    commit id: "Initialize"
    commit id: "Add feature"
    branch feature
    checkout feature
    commit id: "Develop new feature"
    checkout main
    merge feature id: "Merge feature"
gitGraph commit id: "Initialize" commit id: "Add feature" branch feature checkout feature commit id: "Develop new feature" checkout main merge feature id: "Merge feature"

10.3 Branch Operations

Mermaid
gitGraph
    commit
    branch dev
    checkout dev
    commit
    branch feature
    checkout feature
    commit
    checkout dev
    merge feature
    checkout main
    merge dev tag: "v1.0.0"
gitGraph commit branch dev checkout dev commit branch feature checkout feature commit checkout dev merge feature checkout main merge dev tag: "v1.0.0"

11. Kanban

Kanban diagrams are used for task boards and workflow stage management.

Mermaid
kanban
    Todo
        Requirements analysis
        Design review
    In progress
        Frontend development
    Done
        Project initialization
kanban Todo Requirements analysis Design review In progress Frontend development Done Project initialization

12. Quadrant Chart

Quadrant charts are used for prioritization and trend analysis.

Mermaid
quadrantChart
    x-axis Low priority --> High priority
    y-axis Low impact --> High impact
    Urgent tasks: [0.8, 0.9]
    Routine chores: [0.3, 0.4]
    Strategic planning: [0.6, 0.7]
    Trivial odds and ends: [0.2, 0.2]
quadrantChart x-axis Low priority --> High priority y-axis Low impact --> High impact Urgent tasks: [0.8, 0.9] Routine chores: [0.3, 0.4] Strategic planning: [0.6, 0.7] Trivial odds and ends: [0.2, 0.2]

13. Architecture Diagram

Used for cloud infrastructure and service architecture visualization.

Mermaid
architecture-beta
    service api(server)[APIService]
    service db(database)[Database]
    service cache(database)[Cache]
    api:R --< L:db
    api:R --< L:cache
architecture-beta service api(server)[APIService] service db(database)[Database] service cache(database)[Cache] api:R --> L:db api:R --> L:cache

14. Block Diagram

Used for module dependency and network visualization.

Mermaid
block-beta
    columns 3
    a["Module A"] b["Module B"] c["Module C"]
    a --< b
    b --< c
block-beta columns 3 a["Module A"] b["Module B"] c["Module C"] a --> b b --> c

15. C4 Diagram

Used for C4 model visualization of system architecture.

Mermaid
C4Context
    title System context diagram
    Person(user, "User", "System user")
    System(app, "Application system", "Core business system")
    Rel(user, app, "Uses", "HTTPS")
C4Context title System context diagram Person(user, "User", "System user") System(app, "Application system", "Core business system") Rel(user, app, "Uses", "HTTPS")

16. General Tips

16.1 Line Breaks

Use <br> for line breaks inside a node:

Mermaid
flowchart LR
    A[First line
Second line
Third line] --> B[Result]

16.2 Special Characters

If node text contains special characters or keywords (such as end), wrap it in quotes:

Mermaid
flowchart TD
    A["Text with special characters"]
    B["The end keyword"]
flowchart TD A["Text with special characters"] B["The end keyword"]

16.3 Online Debugging

We recommend using the Mermaid Live Editor for online debugging and previewing.

Appendix: Diagram Type Cheat Sheet

Diagram type Keyword Purpose
Flowchart flowchart / graph Process logic, decision trees
Sequence diagram sequenceDiagram Message interaction order
Class diagram classDiagram Object-oriented structure
State diagram stateDiagram-v2 State machines, lifecycles
Gantt chart gantt Project schedule management
Pie chart pie Proportion distribution
ER diagram erDiagram Database relationships
User journey journey User experience flows
Git branch diagram gitGraph Version control visualization
Kanban kanban Task management
Quadrant chart quadrantChart Priority analysis
Architecture diagram architecture-beta Cloud infrastructure
Block diagram block-beta Module dependencies
C4 diagram C4Context System architecture
Comments Leave your thoughts
Guide