Layout Fundamentals¶
Understanding how D2's layout engine works is key to creating well-structured diagrams.
Direction¶
The direction keyword controls how children are arranged within a container.
direction: right # Children flow left-to-right (default for root)
direction: down # Children flow top-to-bottom
direction: left # Children flow right-to-left
direction: up # Children flow bottom-to-top
Example: Horizontal Flow¶
Example: Vertical Flow¶
Direction in Containers¶
Each container can have its own direction:
direction: right
left_box: {
direction: down
a -> b -> c
}
right_box: {
direction: down
x -> y -> z
}
left_box -> right_box
Grid Layout¶
Grid layout gives you explicit control over positioning.
grid-columns¶
Forces elements into a grid with N columns:
Result:
grid-rows¶
Forces elements into a grid with N rows:
Result:
Combining Grid and Direction¶
When both are set, the first one determines fill order:
How the Layout Engine Works¶
D2's layout engine (ELK or dagre) follows these steps:
- Parse the D2 code into a graph structure
- Apply constraints (direction, grid, dimensions)
- Optimize edge routing to minimize crossings
- Position nodes to satisfy all constraints
The Edge Routing Problem¶
The layout engine prioritizes clean edge routing. When you have:
The engine may stack clusters vertically to create a straight edge:
Even if you wanted them side-by-side!
Solution: Grid Override¶
Use grid-columns to force horizontal arrangement:
Now clusters are side-by-side, and the edge routes between them.
Spacing¶
Grid Gap¶
Control spacing in grid layouts:
Vertical and Horizontal Gap¶
Fine-tune spacing separately:
Dimensions¶
Fixed Dimensions¶
Set explicit dimensions:
In Grids¶
Grid cells can have uniform dimensions:
grid-columns: 3
a: { width: 100; height: 50 }
b: { width: 100; height: 50 }
c: { width: 100; height: 50 }
Best Practices¶
-
Start with direction - Set
direction: rightordirection: downat the root level based on your diagram's flow -
Use grid for top-level containers - When you have multiple top-level containers, use
grid-columnsto control their arrangement -
Keep nesting shallow - Deep nesting can confuse the layout engine
-
Be consistent - Use the same direction for similar containers
-
Test early - Render your diagram frequently to catch layout issues early