Grid Layout (v12.3.0+) β
Introduction β
Use layout: grid when you want deterministic row and column placement instead of a layout derived mainly from edge direction. You can place every item explicitly, constrain only a row or column, or let Mermaid fill the remaining cells automatically.
Grid layout supports flowchart, agentflow, state, class, entity relationship, requirement, use case, and mindmap diagrams. Flowchart and agentflow support inline @{ ... } placement metadata. All supported diagram types can use config.grid.placements.
Enable the layout β
Code:
---
config:
layout: grid
---
flowchart TB
A@{ row: 1, column: 1 } --> B@{ row: 1, column: 2 }
B --> C@{ row: 2, column: 2 }
Examples for other diagram types β
The flowchart example above uses inline placement metadata. The following examples use automatic grid placement for the other supported diagram types.
Agentflow β
Code:
---
config:
layout: grid
---
agentflow-beta
request["Receive request"]@{ shape: input, row: 1, column: 1 }
plan["Plan work"]@{ shape: task, row: 1, column: 2 }
run["Run tool"]@{ shape: tool, row: 1, column: 3 }
publish["Publish result"]@{ shape: action, row: 1, column: 4 }
request --> plan --> run --> publish
State diagram β
Code:
---
config:
layout: grid
grid:
columnGap: 300
placements:
Draft: { row: 1, column: 1 }
Review: { row: 1, column: 2 }
Published: { row: 2, column: 2 }
---
stateDiagram-v2
Draft --> Review
Review --> Published
Review --> Draft : changes requested
Class diagram β
Code:
---
config:
layout: grid
grid:
columnGap: 100
rowGap: 100
placements:
Customer: { row: 1, column: 1 }
Order: {row: 1, column: 2}
Payment: {row: 2, column: 2}
Shipment: {row: 1, column: 3}
---
classDiagram
Customer --> Order : places
Customer --> Payment : makes
Order --> Payment : pays with
Order --> Shipment : creates
Entity relationship diagram β
Code:
---
config:
layout: grid
grid:
columnGap: 150
rowGap: 100
placements:
CUSTOMER: { row: 1, column: 1 }
ORDER: { row: 1, column: 2 }
PAYMENT: { row: 2, column: 2 }
LINE_ITEM: { row: 1, column: 3 }
---
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE_ITEM : contains
ORDER ||--o| PAYMENT : has
Requirement diagram β
Code:
---
config:
layout: grid
grid:
columnGap: 200
---
requirementDiagram
requirement checkout {
id: 1
text: "Customers can complete an order"
risk: high
verifymethod: test
}
element storefront {
type: service
docref: "checkout"
}
storefront - satisfies -> checkout
Use case diagram β
Code:
---
config:
layout: grid
grid:
placements:
Customer: {row: 2, column: 1}
Browse: {row: 1, column: 2}
Checkout: {row: 2, column: 2}
Track: {row: 3, column: 2}
---
usecase-beta
actor Customer
Browse("Browse products")
Checkout("Complete checkout")
Track("Track order")
Customer --> Browse
Customer --> Checkout
Customer --> Track
Mindmap β
Code:
---
config:
layout: grid
grid:
placements:
root: {row: 2, column: 2}
Plan: {row: 1, column: 1}
Build: {row: 1, column: 3}
Test: {row: 1, column: 4}
Deploy: {row: 3, column: 3}
---
mindmap
root((Release))
Plan
Build
Test
Deploy
Placement metadata β
Flowchart and agentflow nodes and expanded subgraphs accept four grid-specific metadata keys:
rowcolumnhorizontalAlignverticalAlign
Coordinates are:
- safe integers, including
0and negative values - local to the direct parent group
- sparse but collapsed (rows
1and100render as adjacent occupied tracks)
Rows are ordered from smallest to largest, top to bottom; columns are ordered from smallest to largest, left to right. The values identify tracks, not physical offsets. A graph containing a single node at (-5, 0) renders identically to a graph containing a single node at (1, 1).
Invalid row or column values are rejected during parsing with a GRID_INVALID_COORDINATE error that identifies the placement, field, received value and type, and the safe-integer requirement. This applies to inline metadata, frontmatter, directives, and initialized configuration. Strings (including numeric strings), fractional numbers, null, non-finite numbers, and unsafe integers are rejected without coercion, rounding, or automatic placement. Numeric 1.0 is an integer and is accepted.
In flowcharts using grid layout, unrecognized inline node or subgraph metadata keys produce a console warning naming the item and key. Parsing still succeeds. For example, column 2 (missing the colon) is an unknown key, not a column coordinate, so that column is placed automatically.
When inline metadata and config.grid.placements both set the same property, inline metadata takes precedence.
Code:
---
config:
layout: grid
grid:
rowGap: 32
columnGap: 40
cellGap: 12
---
flowchart TB
A@{ row: 1, column: 1 }
B@{ row: 2, column: 1 }
C@{ row: 2, column: 2, horizontalAlign: right }
A --> B
B --> C
Placement maps β
All supported diagram types can use the global placement map:
Code:
---
config:
layout: grid
grid:
placements:
A: { row: 1, column: 1 }
B: { row: 2, column: 1 }
C: { row: 2, column: 2 }
---
flowchart TB
A --> B
B --> C
Placement-map keys use authored node identifiers when the diagram type provides them. This includes flowchart, agentflow, entity relationship, and mindmap identifiers. Other diagram types use the node ids they emit for layout.
When an authored identifier occurs more than once, use an array to place each occurrence in source order. A single placement object is equivalent to an array with one entry. Occurrences without a matching entry are placed automatically, and extra entries are ignored with a console warning. Inline metadata still takes precedence over the matching placement-map entry.
Code:
---
config:
layout: grid
grid:
placements:
service:
- { row: 1, column: 1 }
- { row: 1, column: 2 }
---
mindmap
root((Services))
service[API]
service[Worker]
service[Automatically placed]
Placement-map keys beginning with __ are removed by Mermaid's recursive configuration sanitizer as a prototype-pollution precaution. For flowchart and agentflow nodes with such ids, use inline placement metadata instead. Inline placement metadata is only supported by flowchart and agentflow; for other diagram types, use node ids that do not begin with __.
Placements for ids that are not present in the diagram are ignored with a console warning. This allows a shared or generated placement map to contain entries for optional nodes.
Automatic placement β
If either coordinate is omitted, Mermaid fills it deterministically:
- explicit
(row, column)cells are reserved first rowonly picks the first free column in that rowcolumnonly picks the first free row in that column- when both are omitted, Mermaid scans row-major using
grid.columnswhen it is greater than0; otherwise, it usesceil(sqrt(itemCount))
Automatic placement runs independently within each group. Two or more direct siblings with the same explicit (row, column) share one cell as a vertical stack in declaration order.
Automatic placement starts at 1 on each omitted axis, regardless of explicit coordinates. Use 0 or negative coordinates to place items above or to the left of the automatic grid.
Alignment and stacking β
horizontalAlign:left,center,rightverticalAlign:top,center,bottom
Horizontal alignment applies to each item. Vertical alignment applies to the whole stack in an explicitly shared cell. Items in the same cell must resolve to the same vertical alignment; otherwise, Mermaid reports GRID_CELL_ALIGNMENT_CONFLICT.
Code:
---
config:
layout: grid
grid:
cellGap: 25
---
flowchart TB
A["Alpha"]@{ row: 1, column: 1, horizontalAlign: left, verticalAlign: bottom }
B["Beta"]@{ row: 1, column: 1, horizontalAlign: right, verticalAlign: bottom }
A --> B
Nested groups β
Groups are laid out recursively from the inside out. Child coordinates are always local to the immediate parent group; diagram direction (TB, BT, LR, RL) does not rotate or mirror the authored grid.
Code:
---
config:
layout: grid
grid:
placements:
A: { row: 1, column: 1 }
B: { row: 2, column: 1 }
C: { row: 1, column: 2 }
G: { row: 1, column: 1 }
---
flowchart TB
subgraph G["Group One"]
A["Alpha"]
B["Beta"]
end
C["Peer"]
A --> C
B --> C
Configuration β
| Setting | Default | Purpose |
|---|---|---|
placements | {} | Maps node ids to placement values. |
columns | 0 | Sets the auto-placement column count. 0 selects it automatically. |
rowGap | 50 | Sets the gap between occupied rows. |
columnGap | 50 | Sets the gap between occupied columns. |
cellGap | 20 | Sets the gap between items stacked in one cell. |
containerPadding | 20 | Sets the minimum padding inside groups. |
titleGap | 8 | Sets the clearance between a group title and its child grid. |
horizontalAlign | center | Sets the default horizontal alignment within a cell. |
verticalAlign | center | Sets the default vertical alignment for a cell stack. |
curve | rounded | Sets the edge rendering curve. |
edgeCornerRadius | 5 | Sets the corner radius for rounded edges. |
lineHops | arc | Draws edge crossings as arcs, gaps, or plain crossings. |
For accepted values and validation rules, see the grid layout configuration reference.
Edge routing β
Grid layout calculates edge routes after positioning the nodes and groups. The calculated route:
- uses horizontal and vertical segments
- avoids measured nodes, unrelated groups, and group titles
- may pass through unused space within a grid cell
- crosses group boundaries when connecting nodes in different groups
- attempts to keep parallel and reverse edges on separate ports and lanes
In dense nested diagrams, parallel hierarchy edges can share part of an internal corridor while keeping distinct endpoint ports. If no valid route exists around node or group geometry, Mermaid reports GRID_ROUTE_NOT_FOUND.
Edge labels are placed after the initial routes are calculated. Mermaid attempts to reroute edges around those labels. If it cannot find a safe bounded detour, an edge can pass through another edge's label rather than failing the whole diagram.
Edge curves β
Grid edges use rounded rendering by default. Set grid.curve to any Mermaid flowchart curve style, including basis, cardinal, catmullRom, step, or rounded.
edgeCornerRadius controls the corner radius for rounded edges. It is ignored by other curve styles, and each corner is automatically limited by the adjacent segment lengths.
Code:
---
config:
layout: grid
grid:
curve: rounded
edgeCornerRadius: 10
---
flowchart TB
A@{ row: 1, column: 1 } --> B@{ row: 2, column: 2 }
Code:
---
config:
layout: grid
grid:
curve: linear
---
flowchart TB
A@{ row: 1, column: 1 } --> B@{ row: 2, column: 2 }
linear and rounded preserve the calculated route corridor. Other curves interpolate between the obstacle-aware route points and can move outside that corridor. The interpolated curve is not revalidated against obstacles.
Edge crossings β
Grid draws a small arc where routed edges cross, distinguishing a crossing from a connection without changing the route or node positions.
Set grid.lineHops in frontmatter, a directive, or mermaid.initialize():
| Value | Behavior |
|---|---|
'arc' | Draw an arc at crossings (default). |
'gap' | Leave a visible gap at crossings. |
false | Draw plain crossings without hops. |
config:
layout: grid
grid:
lineHops: gapLine hops preserve corner radii and arrowhead offsets. The renderer reduces or omits a hop when there is too little space near a bend or endpoint. Smoothing curves such as basis are left unchanged.
Current limits β
Grid layout does not support:
- row or column spanning
- in-cell layouts other than vertical stacking; use a nested subgraph to create a separate grid within a cell
- track-level row/column alignment declarations
- manual absolute coordinates or manual edge waypoints