# Mermaid User Guide

Mermaid is a JavaScript diagramming library that turns plain-text definitions into SVG diagrams — right in the browser. Write a few lines of Markdown-inspired syntax, and Mermaid renders flowcharts, sequence diagrams, Gantt charts, and 24 other diagram types without any server, CLI tool, or image editor. It ships as an npm package (or CDN script), integrates with every major documentation platform (GitHub, GitLab, Notion, Docusaurus, VitePress, Obsidian), and supports 11 themes, 3 visual styles, and per-diagram configuration overrides.

This guide covers **Mermaid v11.14.0** and is organized around what you want to accomplish — from a 30-second "hello world" to production-grade multi-diagram pages.

---

## 1. Quick Start

### Your First Diagram in 30 Seconds

Create an HTML file with this content:

```html
<!DOCTYPE html>
<html>
<head>
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
  </script>
</head>
<body>
  <pre class="mermaid">
    flowchart LR
      A[Start] --> B{Decision}
      B -->|Yes| C[Do Thing]
      B -->|No| D[Skip]
      C --> E[Done]
      D --> E
  </pre>
</body>
</html>
```

Open that file in any modern browser. You'll see a rendered flowchart with boxes, arrows, and labels — no build step, no server.

> [!TIP]
> The fastest way to experiment is the [Mermaid Live Editor](https://mermaid.live). Paste diagram text on the left, see the rendered SVG on the right, and export as SVG or PNG.

### How It Works

1. Mermaid scans the page for elements with `class="mermaid"` (or a selector you configure).
2. It parses the text content of each element as diagram syntax.
3. It replaces the text with a rendered SVG.

That's the entire model. No compilation, no external service, no image files to manage. The diagram definition IS the source of truth.

### Diagram in Markdown (GitHub, GitLab, Docusaurus)

Most platforms that support Mermaid use fenced code blocks:

````markdown
```mermaid
flowchart TD
    A[User Request] --> B[Load Balancer]
    B --> C[App Server 1]
    B --> D[App Server 2]
    C --> E[(Database)]
    D --> E
```
````

GitHub renders this natively in issues, PRs, and Markdown files — no plugin needed.

---

## 2. Installation

### npm / yarn / pnpm

<!-- Tabbed install -->

**npm:**
```bash
npm install mermaid
```

**yarn:**
```bash
yarn add mermaid
```

**pnpm:**
```bash
pnpm add mermaid
```

Then import in your JavaScript/TypeScript:

```javascript
import mermaid from 'mermaid';

mermaid.initialize({ startOnLoad: true });
```

### CDN (No Build Step)

Use the ESM build from jsDelivr:

```html
<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
  mermaid.initialize({ startOnLoad: true });
</script>
```

Or pin to an exact version:

```html
<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11.14.0/dist/mermaid.esm.min.mjs';
</script>
```

> [!IMPORTANT]
> Always use `type="module"` with the ESM build. Without it, the browser treats the script as a classic script and the `import` statement fails with a syntax error.

> [!WARNING]
> The UMD build (`mermaid.min.js`) is still available but the ESM build (`mermaid.esm.min.mjs`) is the recommended path for new projects. The UMD build attaches `mermaid` to `window` globally.

### Requirements

| Requirement | Minimum |
|---|---|
| Node.js (for npm install) | 18+ |
| Browser | Any modern browser with ES module support (Chrome 61+, Firefox 60+, Safari 11+, Edge 79+) |
| Package manager | npm 7+, yarn 1.22+, or pnpm 7+ |

### Using with Bundlers

Mermaid works with Webpack, Vite, Rollup, and esbuild. No special configuration is needed — import and call `initialize()`.

**Vite example (vite.config.js):**
```javascript
// No special mermaid config needed — works out of the box
export default {
  // your normal vite config
};
```

**Webpack note:** If you encounter issues with Webpack 4, upgrade to Webpack 5 or use the CDN approach.

### Using with Frameworks

**React:**
```jsx
import { useEffect, useRef } from 'react';
import mermaid from 'mermaid';

function MermaidDiagram({ chart }) {
  const ref = useRef(null);

  useEffect(() => {
    mermaid.initialize({ startOnLoad: false });
    mermaid.run({ nodes: [ref.current] });
  }, [chart]);

  return <pre className="mermaid" ref={ref}>{chart}</pre>;
}
```

**Vue 3:**
```vue
<template>
  <pre class="mermaid" ref="el">{{ code }}</pre>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import mermaid from 'mermaid';

const props = defineProps(['code']);
const el = ref(null);

onMounted(() => {
  mermaid.initialize({ startOnLoad: false });
  mermaid.run({ nodes: [el.value] });
});
</script>
```

---

## 3. Configuration

Mermaid's behavior is controlled through a configuration object passed to `mermaid.initialize()`. Configuration can also be set per-diagram using directives.

### Global Configuration

```javascript
mermaid.initialize({
  theme: 'default',
  look: 'classic',
  securityLevel: 'strict',
  startOnLoad: true,
  logLevel: 'warn',       // 0=trace, 1=debug, 2=info, 3=warn, 4=error, 5=fatal
  fontFamily: 'sans-serif',
  fontSize: 16,
  maxTextSize: 50000,
  maxEdges: 500,
  htmlLabels: true,
  darkMode: false,
  deterministicIds: false,
  suppressErrorRendering: false,
  wrap: false,
});
```

### Top-Level Configuration Options

| Option | Type | Default | Description |
|---|---|---|---|
| `theme` | string | `'default'` | Color theme. See Themes section below. |
| `look` | string | `'classic'` | Visual style: `'classic'`, `'handDrawn'`, `'neo'` |
| `layout` | string | `'dagre'` | Layout algorithm: `'dagre'` or `'elk'` |
| `securityLevel` | string | `'strict'` | Controls HTML/script handling. See Security section. |
| `startOnLoad` | boolean | `true` | Auto-render `class="mermaid"` elements on page load |
| `logLevel` | number/string | `3` (warn) | Logging verbosity (0=trace through 5=fatal) |
| `fontFamily` | string | `'sans-serif'` | Base font for all text |
| `fontSize` | number | `16` | Base font size in pixels |
| `maxTextSize` | number | `50000` | Maximum characters in a single diagram definition |
| `maxEdges` | number | `500` | Maximum edges before rendering is refused |
| `htmlLabels` | boolean | `true` | Use HTML (`<div>`) labels instead of SVG `<text>` |
| `darkMode` | boolean | `false` | Enable dark mode |
| `deterministicIds` | boolean | `false` | Generate stable element IDs (useful for testing) |
| `suppressErrorRendering` | boolean | `false` | Hide error diagrams on parse failure |
| `wrap` | boolean | `false` | Enable text wrapping in labels |
| `legacyMathML` | boolean | `false` | Use legacy MathML rendering |
| `forceLegacyMathML` | boolean | `false` | Force legacy MathML even when KaTeX is available |

> [!NOTE]
> The `htmlLabels` option at the top level replaces the old `flowchart.htmlLabels` setting, which is deprecated. Set `htmlLabels` at the root level of your config object.

### Per-Diagram Directives

Override configuration for a single diagram by placing a directive at the top:

```
%%{init: {"theme": "dark", "flowchart": {"curve": "basis"}}}%%
flowchart LR
    A --> B --> C
```

Directives support nested objects:

```
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#ff6600"}}}%%
flowchart TD
    A[Orange Node] --> B[Default Node]
```

> [!IMPORTANT]
> Directives are parsed before the diagram, so they must appear on the **very first line** of the diagram definition. A blank line before the directive causes it to be ignored silently.

### Themes

Mermaid ships with 11 built-in themes:

| Theme | Description |
|---|---|
| `default` | Standard colors, light background |
| `base` | Minimal — designed for heavy customization via `themeVariables` |
| `dark` | Dark background with light text |
| `forest` | Green-tinted organic palette |
| `neutral` | Grayscale, high contrast |
| `neo` | Modern clean design |
| `neo-dark` | Neo theme with dark background |
| `redux` | Bold, structured look |
| `redux-dark` | Redux with dark background |
| `redux-color` | Redux with color accents |
| `redux-dark-color` | Redux dark with color accents |

**Set globally:**
```javascript
mermaid.initialize({ theme: 'forest' });
```

**Set per-diagram:**
```
%%{init: {"theme": "dark"}}%%
flowchart LR
    A --> B
```

**Customize theme colors:**
```javascript
mermaid.initialize({
  theme: 'base',
  themeVariables: {
    primaryColor: '#4a86cf',
    primaryTextColor: '#fff',
    primaryBorderColor: '#3a76bf',
    lineColor: '#666',
    secondaryColor: '#f4f4f4',
    tertiaryColor: '#eee',
  },
});
```

### Visual Styles (look)

The `look` option controls the rendering style independent of colors:

| Look | Effect |
|---|---|
| `classic` | Clean vector shapes (default) |
| `handDrawn` | Rough, sketch-like appearance (uses rough.js internally) |
| `neo` | Modern minimalist aesthetic |

```javascript
mermaid.initialize({ look: 'handDrawn', theme: 'neutral' });
```

### Layout Engines

Mermaid supports two layout engines for directed graphs:

**Dagre (default):**
```javascript
mermaid.initialize({ layout: 'dagre' });
```

**ELK (Eclipse Layout Kernel):**
```javascript
mermaid.initialize({ layout: 'elk' });
```

ELK must be loaded separately as an external dependency. It provides more layout options:

| ELK Option | Values | Description |
|---|---|---|
| `mergeEdges` | `true` / `false` | Merge parallel edges between same nodes |
| `nodePlacementStrategy` | `SIMPLE`, `NETWORK_SIMPLEX`, `LINEAR_SEGMENTS`, `BRANDES_KOEPF` | Algorithm for placing nodes vertically |
| `cycleBreakingStrategy` | string | Strategy for handling cycles in the graph |
| `forceNodeModelOrder` | `true` / `false` | Force nodes to appear in definition order |
| `considerModelOrder` | string | How model order influences layout |

```
%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%%
flowchart TD
    A --> B & C
    B --> D
    C --> D
```

### Security Levels

| Level | HTML Tags | Click Events | Use Case |
|---|---|---|---|
| `strict` | Encoded | Disabled | Untrusted user input |
| `loose` | Rendered | Enabled | Trusted internal content |
| `antiscript` | Rendered | Scripts blocked | HTML needed, but no JS execution |
| `sandbox` | Rendered in iframe | Isolated | Maximum isolation |

```javascript
// For user-generated content:
mermaid.initialize({ securityLevel: 'strict' });

// For trusted documentation sites:
mermaid.initialize({ securityLevel: 'loose' });
```

> [!CAUTION]
> Never use `securityLevel: 'loose'` on pages where untrusted users can supply diagram text. Malicious diagram definitions could inject scripts. Use `'strict'` or `'sandbox'` for user-generated content.

### Per-Diagram Configuration Objects

Each diagram type has its own configuration namespace. Pass these as nested objects:

```javascript
mermaid.initialize({
  flowchart: {
    curve: 'basis',
    padding: 20,
    nodeSpacing: 50,
    rankSpacing: 50,
    useMaxWidth: true,
  },
  sequence: {
    diagramMarginX: 50,
    diagramMarginY: 10,
    actorMargin: 50,
    width: 150,
    height: 65,
    boxMargin: 10,
    useMaxWidth: true,
    showSequenceNumbers: false,
  },
  gantt: {
    titleTopMargin: 25,
    barHeight: 20,
    barGap: 4,
    topPadding: 50,
    sidePadding: 75,
    numberSectionStyles: 4,
    axisFormat: '%Y-%m-%d',
  },
});
```

Full list of diagram-specific config namespaces: `flowchart`, `sequence`, `gantt`, `journey`, `timeline`, `class`, `state`, `er`, `pie`, `quadrantChart`, `xyChart`, `requirement`, `architecture`, `mindmap`, `ishikawa`, `kanban`, `gitGraph`, `c4`, `sankey`, `packet`, `block`, `eventmodeling`, `treeView`, `radar`, `venn`, `wardley-beta`.

For detailed configuration of each diagram type, see the *Admin Guide — Configuration Reference*.

---

## 4. Core Usage

Mermaid supports **27 diagram types**. This section groups them by use case and provides syntax, examples, and practical tips for each.

### 4.1 Flow and Process Diagrams

#### Flowchart

The most commonly used diagram type. Supports directions, shapes, links, subgraphs, and styling.

**Directions:**

| Direction | Meaning |
|---|---|
| `TD` or `TB` | Top to bottom |
| `BT` | Bottom to top |
| `LR` | Left to right |
| `RL` | Right to left |

**Basic flowchart:**
```mermaid
flowchart TD
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> B
```

**Node shapes:**

| Syntax | Shape |
|---|---|
| `A[text]` | Rectangle |
| `A(text)` | Rounded rectangle |
| `A([text])` | Stadium (pill) |
| `A[[text]]` | Subroutine |
| `A[(text)]` | Cylindrical (database) |
| `A((text))` | Circle |
| `A>text]` | Asymmetric (flag) |
| `A{text}` | Diamond (decision) |
| `A{{text}}` | Hexagon |
| `A[/text/]` | Parallelogram |
| `A[\text\]` | Parallelogram (alt) |
| `A[/text\]` | Trapezoid |
| `A[\text/]` | Trapezoid (alt) |
| `A(((text)))` | Double circle |

**Link types:**

| Syntax | Style |
|---|---|
| `-->` | Arrow |
| `---` | Line (no arrow) |
| `-.->` | Dotted arrow |
| `-.-` | Dotted line |
| `==>` | Thick arrow |
| `===` | Thick line |
| `--text-->` | Arrow with label |
| `-->|text|` | Arrow with label (alt) |
| `~~>` | Invisible link |

**Multi-target links:**
```mermaid
flowchart LR
    A --> B & C --> D
```

**Subgraphs:**
```mermaid
flowchart TB
    subgraph Frontend
        A[React App] --> B[API Client]
    end
    subgraph Backend
        C[Express Server] --> D[(PostgreSQL)]
    end
    B --> C
```

**Subgraph direction:**
```mermaid
flowchart LR
    subgraph Backend
        direction TB
        API --> DB
        API --> Cache
    end
```

**Styling nodes:**
```mermaid
flowchart LR
    A:::success --> B:::warning
    classDef success fill:#90EE90,stroke:#333
    classDef warning fill:#FFD700,stroke:#333
```

**Styling links:**
```mermaid
flowchart LR
    A --> B --> C
    linkStyle 0 stroke:red,stroke-width:2px
    linkStyle 1 stroke:blue,stroke-width:4px
```

**Click events (requires `securityLevel: 'loose'`):**
```mermaid
flowchart LR
    A[Visit Docs] --> B[API Reference]
    click A "https://example.com" "Open docs" _blank
    click B callback "Trigger callback"
```

**Curve options for flowcharts:**

Set the edge interpolation via `flowchart.curve`:

| Curve | Effect |
|---|---|
| `basis` | Smooth B-spline |
| `bumpX` | Monotone bump (horizontal emphasis) |
| `bumpY` | Monotone bump (vertical emphasis) |
| `cardinal` | Cardinal spline (smooth through points) |
| `catmullRom` | Catmull-Rom spline |
| `linear` | Straight line segments |
| `monotoneX` | Monotone cubic (preserves X monotonicity) |
| `monotoneY` | Monotone cubic (preserves Y monotonicity) |
| `natural` | Natural cubic spline |
| `step` | Step function (sharp corners) |
| `stepAfter` | Step after the data point |
| `stepBefore` | Step before the data point |
| `rounded` | Rounded corners on steps |

```javascript
mermaid.initialize({
  flowchart: { curve: 'cardinal' },
});
```

Or per-diagram:
```
%%{init: {"flowchart": {"curve": "stepBefore"}} }%%
flowchart LR
    A --> B --> C --> D
```

#### Block Diagram

For structured block layouts with columns and spacing control:

```mermaid
block-beta
    columns 3
    a["Frontend"] b["API Gateway"] c["Backend"]
    space down1<[" "]>(down) space
    d["CDN"] e["Load Balancer"] f["Database"]
```

#### Sankey Diagram

Visualize flows and proportions:

```mermaid
sankey-beta
    Agricultural waste,Bio-conversion,124.729
    Bio-conversion,Liquid,0.597
    Bio-conversion,Losses,26.862
    Bio-conversion,Solid,280.322
    Bio-conversion,Gas,81.144
```

### 4.2 Sequence and Interaction Diagrams

#### Sequence Diagram

Model interactions between actors over time:

```mermaid
sequenceDiagram
    participant Browser
    participant CDN
    participant API
    participant DB

    Browser->>CDN: GET /app.js
    CDN-->>Browser: 200 OK (cached)
    Browser->>API: POST /api/login
    API->>DB: SELECT user WHERE email=?
    DB-->>API: User record
    API-->>Browser: 200 JWT token
```

**Arrow types:**

| Syntax | Meaning |
|---|---|
| `->` | Solid line without arrow |
| `-->` | Dotted line without arrow |
| `->>` | Solid line with arrowhead |
| `-->>` | Dotted line with arrowhead |
| `-x` | Solid line with cross (async) |
| `--x` | Dotted line with cross |
| `-)` | Solid line with open arrow (async) |
| `--)` | Dotted line with open arrow |

**Activation boxes:**
```mermaid
sequenceDiagram
    Client->>+Server: Request
    Server->>+Database: Query
    Database-->>-Server: Results
    Server-->>-Client: Response
```

**Loops, alternatives, and options:**
```mermaid
sequenceDiagram
    Client->>Server: authenticate

    alt Valid credentials
        Server-->>Client: 200 OK
    else Invalid
        Server-->>Client: 401 Unauthorized
    end

    opt Has admin role
        Client->>Server: GET /admin
        Server-->>Client: Admin panel
    end

    loop Every 30s
        Client->>Server: heartbeat
        Server-->>Client: ack
    end
```

**Notes:**
```mermaid
sequenceDiagram
    Alice->>Bob: Hello
    Note over Alice,Bob: Encrypted channel
    Note right of Bob: Bob processes
    Bob-->>Alice: Hi back
```

**Sequence numbers:**
```javascript
mermaid.initialize({
  sequence: { showSequenceNumbers: true },
});
```

**Parallel (par):**
```mermaid
sequenceDiagram
    par Send notifications
        Server->>Email: Send email
    and
        Server->>SMS: Send text
    and
        Server->>Push: Send push
    end
```

**Critical region:**
```mermaid
sequenceDiagram
    critical Establish connection
        Service->>DB: connect
    option Network timeout
        Service-->Service: retry
    option Auth failure
        Service-->Log: log error
    end
```

**Actor boxes vs participants:**
```mermaid
sequenceDiagram
    actor User
    participant Browser
    participant Server

    User->>Browser: Click login
    Browser->>Server: POST /login
```

### 4.3 State and Behavior Diagrams

#### State Diagram

Model state machines and transitions:

```mermaid
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing: submit
    Processing --> Completed: success
    Processing --> Failed: error
    Failed --> Processing: retry
    Completed --> [*]
    Failed --> [*]: abandon
```

**Composite states:**
```mermaid
stateDiagram-v2
    [*] --> Active

    state Active {
        [*] --> Idle
        Idle --> Running: start
        Running --> Idle: pause
    }

    Active --> Closed: shutdown
    Closed --> [*]
```

**Forks and joins:**
```mermaid
stateDiagram-v2
    state fork_state <<fork>>
    [*] --> fork_state
    fork_state --> State2
    fork_state --> State3

    state join_state <<join>>
    State2 --> join_state
    State3 --> join_state
    join_state --> State4
    State4 --> [*]
```

**Choice pseudostate:**
```mermaid
stateDiagram-v2
    state check_status <<choice>>
    [*] --> check_status
    check_status --> Approved: if valid
    check_status --> Rejected: if invalid
```

**Notes:**
```mermaid
stateDiagram-v2
    State1: Processing
    note right of State1
        This state handles
        all incoming events
    end note
```

> [!WARNING]
> State diagram syntax is sensitive to the keyword `end note` — it must be on its own line with exactly one space between `end` and `note`. Variations like `endnote` or `end  note` cause parse errors. This is a known issue (see Troubleshooting, #7089).

#### User Journey

Map user experiences with satisfaction ratings:

```mermaid
journey
    title My Working Day
    section Morning
        Wake up: 3: Me
        Commute: 1: Me, Cat
        Start work: 4: Me
    section Afternoon
        Lunch: 5: Me, Colleague
        Meetings: 2: Me
    section Evening
        Go home: 3: Me
        Relax: 5: Me, Cat
```

Satisfaction scores range from 1 (worst) to 5 (best). Colors map automatically.

### 4.4 Structural Diagrams

#### Class Diagram

UML class diagrams with inheritance, composition, and methods:

```mermaid
classDiagram
    class Animal {
        +String name
        +int age
        +makeSound() void
    }

    class Dog {
        +String breed
        +fetch() void
    }

    class Cat {
        +bool indoor
        +purr() void
    }

    Animal <|-- Dog
    Animal <|-- Cat
```

**Relationship types:**

| Syntax | Type |
|---|---|
| `<\|--` | Inheritance |
| `*--` | Composition |
| `o--` | Aggregation |
| `-->` | Association |
| `..>` | Dependency |
| `..\|>` | Realization |
| `--` | Solid link |
| `..` | Dashed link |

**Multiplicity:**
```mermaid
classDiagram
    Customer "1" --> "*" Order : places
    Order "1" --> "1..*" LineItem : contains
    LineItem "*" --> "1" Product : references
```

**Annotations:**
```mermaid
classDiagram
    class Shape {
        <<interface>>
        +area() double
        +perimeter() double
    }

    class Circle {
        +double radius
        +area() double
    }

    Shape <|.. Circle
```

**Visibility modifiers:**

| Prefix | Meaning |
|---|---|
| `+` | Public |
| `-` | Private |
| `#` | Protected |
| `~` | Package/Internal |

**Namespace grouping:**
```mermaid
classDiagram
    namespace com.example.models {
        class User
        class Role
    }
    namespace com.example.services {
        class AuthService
    }
    User --> Role
    AuthService --> User
```

#### Entity Relationship Diagram

Model database schemas:

```mermaid
erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE-ITEM : contains
    PRODUCT ||--o{ LINE-ITEM : "is in"
    CUSTOMER {
        string name
        string email PK
        date created_at
    }
    ORDER {
        int id PK
        date placed_at
        string status
    }
```

**Relationship notation:**

| Left | Right | Meaning |
|---|---|---|
| `\|\|` | `\|\|` | Exactly one to exactly one |
| `\|\|` | `o{` | Exactly one to zero or more |
| `\|\|` | `\|{` | Exactly one to one or more |
| `o\|` | `o{` | Zero or one to zero or more |

#### Architecture Diagram

Visualize system components and their connections:

```mermaid
architecture-beta
    group cloud(cloud)[Cloud]

    service api(server)[API] in cloud
    service db(database)[Database] in cloud
    service cache(database)[Cache] in cloud
    service cdn(internet)[CDN]

    cdn:R --> L:api
    api:R --> L:db
    api:B --> T:cache
```

#### C4 Diagram

Model software architecture using the C4 model:

```mermaid
C4Context
    title System Context Diagram
    Person(user, "User", "A customer")
    System(system, "E-Commerce", "Online store")
    System_Ext(payment, "Payment Gateway", "Stripe")
    Rel(user, system, "Browses and purchases")
    Rel(system, payment, "Processes payments")
```

#### Packet Diagram

Visualize network packet structures:

```mermaid
packet-beta
    0-15: "Source Port"
    16-31: "Destination Port"
    32-63: "Sequence Number"
    64-95: "Acknowledgment Number"
    96-99: "Data Offset"
    100-105: "Reserved"
    106-111: "Flags"
    112-127: "Window Size"
    128-143: "Checksum"
    144-159: "Urgent Pointer"
```

### 4.5 Project Management Diagrams

#### Gantt Chart

Plan and visualize project timelines:

```mermaid
gantt
    title Project Alpha
    dateFormat YYYY-MM-DD

    section Planning
        Requirements     :a1, 2026-01-01, 14d
        Design          :a2, after a1, 10d

    section Development
        Backend API     :b1, after a2, 21d
        Frontend UI     :b2, after a2, 28d
        Integration     :b3, after b1, 7d

    section Testing
        QA Testing      :c1, after b3, 14d
        UAT             :c2, after c1, 7d

    section Launch
        Deploy          :milestone, after c2, 0d
```

**Task statuses:**

| Keyword | Effect |
|---|---|
| `done` | Marks task as completed (filled) |
| `active` | Marks task as in-progress (highlighted) |
| `crit` | Marks task as critical path (red) |
| `milestone` | Zero-duration milestone marker |

```mermaid
gantt
    dateFormat YYYY-MM-DD
    section Sprint 1
        Task A     :done, t1, 2026-01-01, 5d
        Task B     :active, t2, after t1, 3d
        Task C     :crit, t3, after t2, 4d
        Release    :milestone, after t3, 0d
```

**Date formats:** Supported via `dateFormat` — uses d3 time format syntax (`%Y-%m-%d`, `%d/%m/%Y`, etc.). The `axisFormat` controls axis label display.

**Excluding dates:**
```mermaid
gantt
    dateFormat YYYY-MM-DD
    excludes weekends
    excludes 2026-12-25

    section Work
        Task A :t1, 2026-12-20, 10d
```

#### Timeline

Visualize events chronologically:

```mermaid
timeline
    title Product History
    2020 : MVP Launch
         : 100 users
    2021 : Series A
         : Mobile app
         : 10K users
    2022 : Enterprise tier
         : API v2
    2023 : Global expansion
```

#### Kanban Board

Visualize work items across stages:

```mermaid
kanban
    column1[Todo]
        task1[Design mockups]
        task2[Write specs]
    column2[In Progress]
        task3[Build API]
    column3[Done]
        task4[Setup CI/CD]
```

### 4.6 Data Visualization Diagrams

#### Pie Chart

```mermaid
pie title Browser Market Share (2026)
    "Chrome" : 65
    "Safari" : 19
    "Firefox" : 8
    "Edge" : 5
    "Other" : 3
```

#### XY Chart

Plot data on X/Y axes:

```mermaid
xychart-beta
    title "Monthly Revenue"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    y-axis "Revenue ($K)" 0 --> 100
    bar [30, 45, 55, 60, 72, 85]
    line [30, 45, 55, 60, 72, 85]
```

#### Quadrant Chart

Position items in a 2x2 matrix:

```mermaid
quadrantChart
    title Priority Matrix
    x-axis Low Impact --> High Impact
    y-axis Low Effort --> High Effort
    quadrant-1 Plan carefully
    quadrant-2 Do first
    quadrant-3 Delegate
    quadrant-4 Quick wins
    Feature A: [0.8, 0.3]
    Feature B: [0.2, 0.7]
    Feature C: [0.7, 0.8]
    Feature D: [0.3, 0.2]
```

#### Radar Chart

Compare multiple dimensions:

```mermaid
radar-beta
    title Team Skills Assessment
    axis1 Frontend
    axis2 Backend
    axis3 DevOps
    axis4 Testing
    axis5 Design
    "Alice" : [4, 5, 2, 3, 4]
    "Bob" : [3, 4, 5, 4, 2]
```

#### Venn Diagram

Show set relationships:

```mermaid
venn-beta
    title Tech Stack Overlap
    set1[Frontend]
    set2[Backend]
    set3[DevOps]
    intersection12[Full Stack]
    intersection123[Unicorn]
```

#### Treemap

Visualize hierarchical data proportionally:

```mermaid
treemap-beta
    root[Portfolio]
        stocks[Stocks]
            tech[Tech 40%]
            health[Health 25%]
        bonds[Bonds]
            govt[Government 20%]
            corp[Corporate 15%]
```

### 4.7 Thinking and Analysis Diagrams

#### Mindmap

Organize ideas hierarchically:

```mermaid
mindmap
    root((Project Plan))
        Backend
            API Design
            Database
            Auth
        Frontend
            Components
            State Management
            Routing
        DevOps
            CI/CD
            Monitoring
            Docker
```

**Node shapes in mindmaps:**
- `((text))` — circle (typically root)
- `(text)` — rounded rectangle
- `[text]` — square
- `))text((` — bang (explosion)
- `)text(` — cloud

#### Ishikawa (Fishbone) Diagram

Root-cause analysis:

```mermaid
ishikawa-beta
    title Production Outage
    Causes
        People
            Understaffed
            Training gaps
        Process
            No runbook
            Missing alerts
        Technology
            Single point of failure
            No auto-scaling
        Environment
            Network congestion
            DNS propagation
```

#### Wardley Map

Strategic positioning:

```mermaid
wardley-beta
    title E-Commerce Platform
    anchor User [0.95, 0.63]
    component Website [0.85, 0.55]
    component Payment [0.70, 0.70]
    component Search [0.60, 0.40]
    component Database [0.50, 0.75]
    User --> Website
    Website --> Payment
    Website --> Search
    Website --> Database
```

### 4.8 Development Diagrams

#### Git Graph

Visualize branching and merging strategies:

```mermaid
gitGraph
    commit id: "init"
    branch develop
    checkout develop
    commit id: "feat-1"
    commit id: "feat-2"
    checkout main
    merge develop id: "v1.0" tag: "v1.0"
    branch hotfix
    commit id: "fix-1"
    checkout main
    merge hotfix id: "v1.0.1" tag: "v1.0.1"
    checkout develop
    merge main
    commit id: "feat-3"
```

**Git graph options:**
```javascript
mermaid.initialize({
  gitGraph: {
    showBranches: true,
    showCommitLabel: true,
    mainBranchName: 'main',
    mainBranchOrder: 0,
  },
});
```

#### Requirement Diagram

Trace requirements and their relationships:

```mermaid
requirementDiagram
    requirement high_availability {
        id: REQ-001
        text: System uptime must exceed 99.9%
        risk: high
        verifymethod: test
    }

    element load_balancer {
        type: system
    }

    load_balancer - satisfies -> high_availability
```

#### Event Modeling

Model event-driven systems:

```mermaid
eventmodeling-beta
    participant User
    participant System
    participant Admin

    User -> System: PlaceOrder
    System -> System: OrderPlaced
    System -> User: OrderConfirmation
    Admin -> System: QueryOrders
    System -> Admin: OrderReport
```

#### Tree View

Display hierarchical structures:

```mermaid
tree-view-beta
    root[File System]
        src
            index.ts
            utils.ts
        tests
            index.test.ts
        package.json
```

---

## 5. Common Tasks

### Recipe 1: Render Diagrams Dynamically (SPA)

When your page content changes after initial load (single-page apps, dynamic tabs):

```javascript
// Don't use startOnLoad for SPAs
mermaid.initialize({ startOnLoad: false });

// Render specific elements on demand
async function renderDiagrams(containerElement) {
  const nodes = containerElement.querySelectorAll('.mermaid');
  await mermaid.run({ nodes: Array.from(nodes) });
}
```

### Recipe 2: Validate Diagram Syntax Before Rendering

```javascript
try {
  await mermaid.parse('flowchart LR\n  A --> B');
  console.log('Valid syntax');
} catch (error) {
  console.error('Invalid:', error.message);
}
```

### Recipe 3: Render to String (Server-Side or Export)

```javascript
const { svg } = await mermaid.render('diagram-id', `
  flowchart TD
    A --> B --> C
`);
// svg contains the complete SVG string
document.getElementById('output').innerHTML = svg;
```

### Recipe 4: Suppress Error Diagrams

By default, Mermaid renders an error diagram when syntax is invalid. To hide errors:

```javascript
mermaid.initialize({ suppressErrorRendering: true });
```

### Recipe 5: Custom Error Handler

```javascript
mermaid.setParseErrorHandler((error, hash) => {
  console.warn('Mermaid parse error:', error);
  // Show your own error UI instead
});
```

### Recipe 6: Register External/Plugin Diagrams

```javascript
import mermaid from 'mermaid';
import zenuml from '@mermaid-js/mermaid-zenuml';

await mermaid.registerExternalDiagrams([zenuml]);
mermaid.initialize({ startOnLoad: true });
```

### Recipe 7: Use Hand-Drawn Style for Presentations

```javascript
mermaid.initialize({
  look: 'handDrawn',
  theme: 'neutral',
});
```

### Recipe 8: Dark Mode Page

```javascript
mermaid.initialize({
  theme: 'dark',
  darkMode: true,
});
```

### Recipe 9: Custom Theme Colors

```javascript
mermaid.initialize({
  theme: 'base',
  themeVariables: {
    primaryColor: '#1a1a2e',
    primaryTextColor: '#e0e0e0',
    primaryBorderColor: '#16213e',
    lineColor: '#0f3460',
    secondaryColor: '#533483',
    tertiaryColor: '#e94560',
    background: '#0a0a0a',
  },
});
```

### Recipe 10: Deterministic IDs for Testing

When snapshot-testing rendered SVGs, random IDs cause false diffs:

```javascript
mermaid.initialize({ deterministicIds: true });
```

### Recipe 11: Increase Text/Edge Limits for Large Diagrams

```javascript
mermaid.initialize({
  maxTextSize: 200000,  // Default 50,000
  maxEdges: 2000,       // Default 500
});
```

### Recipe 12: Flowchart with Database and Multiple Shapes

```mermaid
flowchart LR
    U([User]) --> LB{Load Balancer}
    LB --> S1[Server 1]
    LB --> S2[Server 2]
    S1 --> DB[(PostgreSQL)]
    S2 --> DB
    S1 --> C{{Cache}}
    S2 --> C
```

### Recipe 13: Sequence Diagram with Background Colors (rect)

```mermaid
sequenceDiagram
    participant A as Auth Service
    participant U as User
    participant D as Database

    rect rgb(200, 220, 255)
        Note over A,D: Authentication Flow
        U->>A: Login request
        A->>D: Verify credentials
        D-->>A: User found
        A-->>U: JWT token
    end
```

### Recipe 14: Gantt with Sections and Dependencies

```mermaid
gantt
    title Q1 Roadmap
    dateFormat YYYY-MM-DD
    axisFormat %b %d

    section Backend
        API v2           :b1, 2026-01-06, 21d
        Database migration:b2, after b1, 14d

    section Frontend
        New dashboard    :f1, 2026-01-06, 28d
        Mobile responsive:f2, after f1, 14d

    section QA
        Integration tests:q1, after b2, 7d
        Performance tests:q2, after q1, 7d
        Release          :milestone, after q2, 0d
```

### Recipe 15: Mindmap for Sprint Planning

```mermaid
mindmap
    root((Sprint 42))
        Must Have
            User auth
            Payment flow
        Should Have
            Dashboard
            Notifications
        Nice to Have
            Dark mode
            Export PDF
        Tech Debt
            Upgrade React
            Fix flaky tests
```

### Recipe 16: ER Diagram for a Full Schema

```mermaid
erDiagram
    USER ||--o{ POST : writes
    USER ||--o{ COMMENT : writes
    POST ||--o{ COMMENT : has
    POST ||--o{ TAG : tagged_with
    USER {
        uuid id PK
        varchar username UK
        varchar email UK
        timestamp created_at
    }
    POST {
        uuid id PK
        uuid author_id FK
        text title
        text body
        timestamp published_at
    }
    COMMENT {
        uuid id PK
        uuid user_id FK
        uuid post_id FK
        text body
    }
    TAG {
        int id PK
        varchar name UK
    }
```

### Recipe 17: Pie Chart with Custom Theme

```
%%{init: {"theme": "base", "themeVariables": {"pie1": "#ff6384", "pie2": "#36a2eb", "pie3": "#ffce56"}} }%%
pie title Budget Allocation
    "Engineering" : 45
    "Marketing" : 25
    "Operations" : 20
    "Other" : 10
```

### Recipe 18: C4 Container Diagram

```mermaid
C4Container
    title Container Diagram

    Person(user, "User", "A customer of the system")

    Container_Boundary(system, "System") {
        Container(web, "Web App", "React", "Delivers static content")
        Container(api, "API", "Node.js", "Handles business logic")
        ContainerDb(db, "Database", "PostgreSQL", "Stores data")
    }

    Rel(user, web, "Uses", "HTTPS")
    Rel(web, api, "Calls", "JSON/HTTPS")
    Rel(api, db, "Reads/Writes", "SQL")
```

### Recipe 19: State Diagram with Notes and Concurrency

```mermaid
stateDiagram-v2
    [*] --> Draft

    state "Review Process" as review {
        [*] --> PeerReview
        PeerReview --> SecurityReview
        SecurityReview --> [*]
    }

    Draft --> review: submit
    review --> Published: approved
    review --> Draft: rejected
    Published --> Archived: expire
    Archived --> [*]

    note right of Draft: Author can edit freely
    note right of Published: Visible to all users
```

### Recipe 20: XY Chart with Bar and Line

```mermaid
xychart-beta
    title "Performance Metrics"
    x-axis ["v1.0", "v1.1", "v1.2", "v1.3", "v2.0"]
    y-axis "Response Time (ms)" 0 --> 500
    bar [450, 380, 320, 290, 150]
    line [450, 380, 320, 290, 150]
```

### Recipe 21: Quadrant Chart for Feature Prioritization

```mermaid
quadrantChart
    title Feature Priority Matrix
    x-axis "Low Business Value" --> "High Business Value"
    y-axis "Low Complexity" --> "High Complexity"
    quadrant-1 "Strategic — Plan Well"
    quadrant-2 "Quick Wins — Do Now"
    quadrant-3 "Fill-ins — Delegate"
    quadrant-4 "Big Bets — Invest"
    SSO: [0.8, 0.7]
    Dark Mode: [0.3, 0.2]
    API v3: [0.9, 0.9]
    Logo Update: [0.1, 0.1]
    Mobile App: [0.7, 0.5]
```

### Recipe 22: Git Graph Showing GitFlow

```mermaid
gitGraph
    commit id: "Initial"
    branch develop
    commit id: "Setup CI"
    branch feature/auth
    commit id: "Add login"
    commit id: "Add OAuth"
    checkout develop
    merge feature/auth id: "Merge auth"
    branch feature/payments
    commit id: "Stripe integration"
    checkout develop
    merge feature/payments
    checkout main
    merge develop id: "Release v1.0" tag: "v1.0"
```

### Recipe 23: Architecture Diagram for Microservices

```mermaid
architecture-beta
    group vpc(cloud)[AWS VPC]

    service alb(internet)[ALB] in vpc
    service users(server)[Users API] in vpc
    service orders(server)[Orders API] in vpc
    service rds(database)[RDS] in vpc
    service redis(database)[ElastiCache] in vpc

    alb:R --> L:users
    alb:R --> L:orders
    users:R --> L:rds
    orders:R --> L:rds
    users:B --> T:redis
    orders:B --> T:redis
```

### Recipe 24: Multiple Diagrams on One Page

```html
<pre class="mermaid">
flowchart LR
    A --> B
</pre>

<pre class="mermaid">
sequenceDiagram
    Alice->>Bob: Hi
</pre>

<pre class="mermaid">
pie title Distribution
    "A" : 40
    "B" : 60
</pre>

<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
  mermaid.initialize({ startOnLoad: true, theme: 'default' });
</script>
```

### Recipe 25: Using ELK Layout for Complex Graphs

```
%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%%
flowchart TD
    A --> B & C & D
    B --> E
    C --> E & F
    D --> F & G
    E --> H
    F --> H
    G --> H
```

### Recipe 26: Responsive Diagrams with useMaxWidth

```javascript
mermaid.initialize({
  flowchart: { useMaxWidth: true },
  sequence: { useMaxWidth: true },
});
```

This makes diagrams scale to fit their container width instead of using a fixed size.

### Recipe 27: Register Custom Icon Packs

```javascript
const iconPack = {
  prefix: 'custom',
  icons: {
    server: { body: '<path d="..."/>', width: 24, height: 24 },
    database: { body: '<path d="..."/>', width: 24, height: 24 },
  },
};
mermaid.registerIconPacks([iconPack]);
```

### Recipe 28: Sequence Diagram with Auto-numbering and Boxes

```mermaid
sequenceDiagram
    autonumber
    box rgb(200,200,255) Frontend
        participant Browser
        participant Worker as Service Worker
    end
    box rgb(200,255,200) Backend
        participant API
        participant Queue
    end

    Browser->>API: Submit job
    API->>Queue: Enqueue
    Queue-->>API: Job ID
    API-->>Browser: 202 Accepted
    Worker->>API: Poll status
    API-->>Worker: Complete
    Worker->>Browser: Notify user
```

### Recipe 29: Flowchart with Markdown in Labels

```mermaid
flowchart LR
    A["`**Bold** label with
    _italic_ text`"] --> B["`Code: \`npm install\``"]
```

Markdown in labels requires backtick-wrapped strings (`` ` `` delimiters inside `"` quotes).

### Recipe 30: Toggle Theme Based on System Preference

```javascript
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

mermaid.initialize({
  theme: prefersDark ? 'dark' : 'default',
  darkMode: prefersDark,
});

// Re-render on theme change
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
  mermaid.initialize({
    theme: e.matches ? 'dark' : 'default',
    darkMode: e.matches,
  });
  // Re-render existing diagrams
  mermaid.run();
});
```

---

## 6. Troubleshooting

### Problem: Diagram not rendering — blank space where diagram should be

**Cause:** `mermaid.initialize()` was not called, or `startOnLoad` is `false` and `mermaid.run()` was never called.

**Fix:**
```javascript
mermaid.initialize({ startOnLoad: true });
// OR
mermaid.initialize({ startOnLoad: false });
mermaid.run(); // Call explicitly after DOM is ready
```

### Problem: "Maximum text size exceeded" error

**Cause:** Diagram definition exceeds `maxTextSize` (default 50,000 characters).

**Fix:**
```javascript
mermaid.initialize({ maxTextSize: 200000 });
```

### Problem: "Too many edges" error

**Cause:** Diagram exceeds `maxEdges` limit (default 500).

**Fix:**
```javascript
mermaid.initialize({ maxEdges: 2000 });
```

### Problem: Import fails — "Cannot use import statement outside a module"

**Cause:** The `<script>` tag is missing `type="module"`.

**Fix:**
```html
<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
</script>
```

### Problem: CSS classes not working on flowchart nodes (GitHub #3526)

**Cause:** In Mermaid v8.8.0+, the CSS class syntax changed. Classes applied via `:::` may not work if the class definition uses incompatible selectors.

**Fix:** Define classes with `classDef` and ensure selectors target SVG elements:
```mermaid
flowchart LR
    A:::highlight --> B
    classDef highlight fill:#ff0,stroke:#333,stroke-width:2px
```

Avoid CSS selectors that assume HTML elements — Mermaid renders SVG.

### Problem: Internal error on subgraph with numeric identifier (GitHub #7609)

**Cause:** Using a pure number as a subgraph identifier triggers a parsing error.

**Fix:** Prefix numeric identifiers with a letter:
```mermaid
flowchart TD
    subgraph s1[Phase 1]
        A --> B
    end
```

### Problem: fontSize themeVariable setting is ignored (GitHub #6142)

**Cause:** The `fontSize` themeVariable does not propagate to all diagram elements in some themes.

**Fix:** Set `fontSize` at the top-level config instead of in `themeVariables`:
```javascript
mermaid.initialize({
  fontSize: 14,
  // NOT in themeVariables
});
```

### Problem: Consecutive LaTeX equations with text fail to render (GitHub #7034)

**Cause:** The KaTeX integration has trouble parsing sequences of `$$...$$` blocks with inline text between them.

**Fix:** Separate LaTeX blocks with diagram elements rather than inline text between them. If you need math rendering, ensure `legacyMathML` is set appropriately:
```javascript
mermaid.initialize({ legacyMathML: false });
```

### Problem: Flowchart node border syntax not working (GitHub #7502)

**Cause:** Custom border styling via inline syntax may not apply correctly in certain renderers.

**Fix:** Use `classDef` with explicit `stroke` properties:
```mermaid
flowchart LR
    A:::bordered --> B
    classDef bordered stroke:#f00,stroke-width:3px
```

### Problem: State diagram "end note" detection incorrect (GitHub #7089)

**Cause:** The parser incorrectly detects `end note` within state names or transitions that contain the substring.

**Fix:** Avoid the substring `end note` in state names. If you need a note, ensure `end note` appears on its own line:
```mermaid
stateDiagram-v2
    State1
    note right of State1
        This is a note
    end note
```

### Problem: Class diagram self-referential multiplicity displayed multiple times (GitHub #7560)

**Cause:** When a class has a relationship to itself with multiplicity labels, the labels render more than once.

**Fix:** This is a known rendering bug. Workaround: simplify self-referential relationships or omit multiplicity on self-references:
```mermaid
classDiagram
    Node --> Node : "contains children"
```

### Problem: Implementation/realization arrow not rendered on mobile/iOS (GitHub #7518)

**Cause:** SVG marker rendering differences on WebKit/iOS cause dashed arrows with hollow tips to disappear.

**Fix:** Test on desktop first. For iOS-targeted content, consider using solid arrows (`-->`) and adding a note about the relationship type.

### Problem: Diagram directive is silently ignored

**Cause:** The `%%{init: ...}%%` directive is not on the very first line, or there's a blank line before it.

**Fix:** Ensure the directive is the absolute first line:
```
%%{init: {"theme": "forest"}}%%
flowchart TD
    A --> B
```

### Problem: Click events do nothing

**Cause:** Security level is set to `strict` (default), which disables click handlers.

**Fix:**
```javascript
mermaid.initialize({ securityLevel: 'loose' });
```

> [!CAUTION]
> Only use `'loose'` security on trusted content. See the Security section for details.

### Problem: Diagrams render differently on each page load

**Cause:** Non-deterministic element IDs cause different SVG structure. Layout algorithms may also produce slightly different results.

**Fix:**
```javascript
mermaid.initialize({ deterministicIds: true });
```

### Problem: Mermaid renders in `<pre>` tags but not in `<div>` tags

**Cause:** By default Mermaid looks for elements with `class="mermaid"`. Both `<pre>` and `<div>` work, but the selector must match.

**Fix:** Either use `class="mermaid"` on your elements, or call `mermaid.run()` with a custom selector:
```javascript
await mermaid.run({
  querySelector: '.my-diagram',
});
```

### Problem: SVG is cut off or clipped

**Cause:** The container has constrained dimensions and `useMaxWidth` is `true`.

**Fix:** Ensure the container can expand, or set `useMaxWidth: false` for fixed-size output:
```javascript
mermaid.initialize({
  flowchart: { useMaxWidth: false },
});
```

### Problem: Diagram renders but text is garbled or missing

**Cause:** The specified font is not available in the browser.

**Fix:** Use a web-safe font or load the font before Mermaid renders:
```javascript
mermaid.initialize({
  fontFamily: '"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
});
```

### Problem: ELK layout produces unexpected node positions

**Cause:** ELK has different layout defaults than Dagre. Node order in the definition matters more with ELK.

**Fix:** Use ELK-specific options:
```javascript
mermaid.initialize({
  flowchart: {
    defaultRenderer: 'elk',
    elk: {
      nodePlacementStrategy: 'NETWORK_SIMPLEX',
      forceNodeModelOrder: true,
    },
  },
});
```

### Problem: Mermaid.run() throws "No elements found"

**Cause:** Called before the DOM has the mermaid elements, or elements don't have `class="mermaid"`.

**Fix:** Wait for DOM ready, or pass nodes explicitly:
```javascript
document.addEventListener('DOMContentLoaded', () => {
  mermaid.run();
});
```

### Problem: Duplicate rendering — diagrams appear twice

**Cause:** `startOnLoad: true` AND a manual `mermaid.run()` call — the diagram renders twice.

**Fix:** Use one or the other:
```javascript
// Option A: auto-render
mermaid.initialize({ startOnLoad: true });
// Don't call mermaid.run()

// Option B: manual render
mermaid.initialize({ startOnLoad: false });
mermaid.run();
```

### Problem: Flowchart.htmlLabels setting has no effect

**Cause:** `flowchart.htmlLabels` is deprecated.

**Fix:** Use the top-level `htmlLabels` option:
```javascript
mermaid.initialize({
  htmlLabels: true,  // Correct — top level
  // flowchart: { htmlLabels: true }  // DEPRECATED — don't use
});
```

### Problem: Diagram works in Live Editor but not on my page

**Cause:** Version mismatch — the Live Editor may use a newer Mermaid version, or your page has conflicting CSS.

**Fix:**
1. Check your Mermaid version matches the Live Editor version.
2. Inspect for CSS conflicts (especially `pre`, `code`, or SVG styles).
3. Check the browser console for parse errors.

### Problem: Gantt chart dates display incorrectly

**Cause:** `dateFormat` doesn't match the date strings in your task definitions.

**Fix:** Ensure format matches:
```mermaid
gantt
    dateFormat YYYY-MM-DD
    section Tasks
        Task A :2026-01-15, 10d
```

If using `DD/MM/YYYY`, set `dateFormat DD/MM/YYYY`.

### Problem: Sandbox mode iframe has wrong dimensions

**Cause:** When `securityLevel: 'sandbox'`, Mermaid renders in an iframe whose dimensions may not match the SVG content.

**Fix:** Let the container control sizing. Avoid fixed heights on the parent element. Consider using `'strict'` or `'antiscript'` instead if iframe isolation isn't needed.

> [!TIP]
> For most documentation sites, `securityLevel: 'strict'` (the default) is the right choice. Reserve `'sandbox'` for cases where you need complete iframe isolation.

### Problem: Theme changes don't take effect after initialization

**Cause:** `mermaid.initialize()` sets the config but doesn't re-render existing diagrams.

**Fix:** After changing config, call `mermaid.run()` to re-render:
```javascript
mermaid.initialize({ theme: 'dark' });
mermaid.run(); // Re-render with new theme
```

> [!WARNING]
> Re-rendering replaces the SVG content of all matched elements. If you've attached event listeners directly to SVG elements, they will be lost on re-render.

---

## 7. FAQ

**Q1: What diagram types does Mermaid support?**

Mermaid supports 27 diagram types: flowchart, sequence, class, state, ER (entity-relationship), Gantt, pie, user journey, C4, mindmap, timeline, quadrant chart, XY chart, requirement, git graph, sankey, block, architecture, packet, kanban, ishikawa (fishbone), radar, venn, treemap, event modeling, tree view, and wardley map. Types marked "beta" (e.g., `sankey-beta`) are stable enough for production but the syntax may evolve.

**Q2: Does Mermaid have a CLI?**

No. Mermaid is a browser-side JavaScript library. There is a separate community project, `mermaid-cli` (`@mermaid-js/mermaid-cli`), which wraps Mermaid in Puppeteer to render diagrams from the command line — but that is a distinct package, not part of the core library.

**Q3: Can I use Mermaid without npm/Node.js?**

Yes. Use the CDN approach — a single `<script type="module">` tag is all you need. No build step, no Node.js required.

**Q4: Which platforms support Mermaid natively?**

GitHub (issues, PRs, Markdown files), GitLab, Notion, Azure DevOps, Docusaurus, VitePress, Obsidian, Typora, and many others render Mermaid code blocks natively. Check your platform's documentation for the exact syntax (usually a fenced code block with `mermaid` as the language).

**Q5: How do I export diagrams as images?**

Use the Mermaid Live Editor (mermaid.live) for manual export. For programmatic export, call `mermaid.render()` to get the SVG string, then convert SVG to PNG using a library like `sharp` or `canvas`.

**Q6: Can I customize colors beyond the built-in themes?**

Yes. Use `theme: 'base'` with `themeVariables` to set individual colors. You can control `primaryColor`, `secondaryColor`, `tertiaryColor`, `lineColor`, text colors, and more.

**Q7: What's the difference between `startOnLoad` and `mermaid.run()`?**

`startOnLoad: true` automatically calls the rendering logic when the page loads (on `DOMContentLoaded`). `mermaid.run()` triggers rendering explicitly. Use `startOnLoad: false` + `mermaid.run()` in SPAs or when you need to control timing.

**Q8: How do I render diagrams added dynamically to the DOM?**

Set `startOnLoad: false`, add your diagram elements to the DOM, then call:
```javascript
await mermaid.run({ nodes: [newElement] });
```

**Q9: What is the `look` option?**

The `look` controls the visual rendering style: `'classic'` (clean SVG shapes), `'handDrawn'` (sketchy/rough appearance), or `'neo'` (modern minimalist). It's independent of the color theme.

**Q10: Can I use Mermaid with TypeScript?**

Yes. Mermaid ships TypeScript type definitions. Import normally:
```typescript
import mermaid, { type MermaidConfig } from 'mermaid';
```

**Q11: What's the maximum diagram size?**

Controlled by `maxTextSize` (default 50,000 characters) and `maxEdges` (default 500). Increase both for large diagrams, but expect slower rendering.

**Q12: How do I enable LaTeX/math in diagrams?**

Mermaid supports KaTeX for math rendering. Use `$$...$$` syntax in labels. If KaTeX isn't loading, check the `legacyMathML` and `forceLegacyMathML` options.

**Q13: Can I have multiple diagram types on one page?**

Yes. Each `<pre class="mermaid">` block is independent. You can mix flowcharts, sequence diagrams, pie charts, etc. on the same page with one `initialize()` call.

**Q14: How does `securityLevel` affect my diagrams?**

`strict` (default) encodes HTML tags and disables click events. `loose` allows HTML and click events. `antiscript` allows HTML but blocks JavaScript. `sandbox` renders in an iframe.

**Q15: What's the difference between Dagre and ELK layout?**

Dagre is the default, fast layout engine. ELK (Eclipse Layout Kernel) provides more control over node placement and edge routing, but requires an additional dependency and is generally slower. Use ELK for complex graphs where Dagre produces poor layouts.

**Q16: How do I add links/URLs to nodes?**

Use click events with `securityLevel: 'loose'`:
```mermaid
flowchart LR
    A[Visit Site]
    click A "https://example.com" _blank
```

**Q17: Can I wrap long text in nodes?**

Enable wrapping globally with `wrap: true`, or use Markdown syntax in labels with backtick delimiters for manual line breaks.

**Q18: How do I use Mermaid in a React app?**

Initialize with `startOnLoad: false`, use a ref to the DOM element, and call `mermaid.run()` in `useEffect`. See Recipe 1 and the React example in the Installation section.

**Q19: What does `deterministicIds` do?**

When `true`, Mermaid generates stable, predictable element IDs in the SVG output. This is essential for snapshot testing — without it, IDs change on each render.

**Q20: Why do my diagrams look different from the documentation examples?**

Check your Mermaid version — examples may target a newer version. Also check your theme, look, and layout settings, as these change the visual output significantly.

**Q21: Can I register custom diagram types?**

Yes, via `mermaid.registerExternalDiagrams()`. External diagrams must follow Mermaid's plugin API. Community examples include `@mermaid-js/mermaid-zenuml`.

**Q22: How do I register custom layout algorithms?**

Use `mermaid.registerLayoutLoaders()` to register layout plugins that implement the layout interface.

**Q23: What's the `neo` theme vs. the `neo` look?**

They're different settings. `theme: 'neo'` controls the color palette. `look: 'neo'` controls the rendering style (shape aesthetics). You can combine any theme with any look.

**Q24: How do I debug rendering issues?**

Set `logLevel` to `0` (trace) or `1` (debug) to see detailed parsing and rendering logs in the browser console:
```javascript
mermaid.initialize({ logLevel: 0 });
```

**Q25: Can I control the direction of a subgraph independently?**

Yes. Use the `direction` keyword inside a subgraph:
```mermaid
flowchart LR
    subgraph Backend
        direction TB
        API --> DB
    end
```

**Q26: What are the beta diagram types?**

Several diagram types use a `-beta` suffix in their syntax keyword (e.g., `sankey-beta`, `radar-beta`, `venn-beta`, `wardley-beta`, `xychart-beta`). These are functional and usable but their syntax may change in future versions.

**Q27: How do I prevent Mermaid from rendering certain elements?**

Mermaid only targets elements matching the configured selector (default: `class="mermaid"`). Don't use that class on elements you don't want rendered. Alternatively, use `mermaid.run({ nodes: [...] })` to target specific elements.

**Q28: Is Mermaid accessible?**

Mermaid renders SVGs which have limited built-in accessibility. Add `aria-label` and `role="img"` to diagram containers, and consider providing text alternatives for screen readers.

**Q29: Can I animate Mermaid diagrams?**

Mermaid doesn't support animation natively. You can apply CSS animations to the rendered SVG elements after rendering, but this requires knowledge of the SVG structure.

**Q30: How often is Mermaid updated?**

Mermaid is actively maintained with regular releases. Major versions may include breaking syntax changes for beta diagram types. Pin your version in production to avoid unexpected changes.

---

_Generated May 2026 from mermaid-js/mermaid at 8b52e53. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
