Notion中Mermaid流程图对齐与布局优化技术求助
To achieve your desired layout without empty nodes, you can use invisible subgraphs to group child nodes (which automatically centers the parent above all children) and adjust Mermaid's built-in layout configuration to increase spacing. For widening parent nodes based on child count, you'll need to apply custom styles manually since Mermaid doesn't support dynamic width adjustment based on child nodes natively.
Step 1: Remove Empty Nodes & Center Alignment
Replace empty nodes with invisible subgraphs for each set of child nodes. This ensures the parent node is centered above all its children without extra nodes.
Step 2: Increase Spacing
Adjust nodeSpacing (horizontal space between nodes in the same rank) and rankSpacing (vertical space between ranks) in the Mermaid init config to improve readability.
Step 3: Widen Parent Nodes
Add custom classDef or inline style commands to set appropriate widths for parent nodes based on the number of children they have.
Final Code Example
%%{ init: { 'theme': 'base', 'flowchart': { 'curve': 'stepAfter', 'nodeSpacing': 80, # Increase horizontal space between nodes 'rankSpacing': 100 # Increase vertical space between ranks } } }%% # Define styles: invisible subgraphs and parent node widths classDef subgraphInvisible fill:none, stroke:none; classDef parent3Children width:220px; # For parents with 3 children classDef parent2Children width:160px; # For parents with 2 children classDef left-align text-align:left; # Parent -> Invisible Subgraph -> Children Snack:::parent3Children --- subgraph SnackKids Drink:::parent2Children Candy:::parent3Children Chips end Drink --- subgraph DrinkKids SoftDrink:::parent3Children FruitJuice end SoftDrink --- subgraph SoftDrinkKids CocaCola Sprite MountainDew end Candy --- subgraph CandyKids Chocolate Jelly HardCandy end # Apply invisible style to subgraphs class SnackKids, DrinkKids, SoftDrinkKids, CandyKids subgraphInvisible;
Explanation
- Invisible Subgraphs: The subgraphs are styled to have no fill or stroke, so they're not visible. Connecting the parent to the subgraph ensures the parent is centered above all child nodes in the subgraph.
- Spacing Config:
nodeSpacingandrankSpacingvalues are adjustable (tweak these numbers to match your preference) to add more breathing room between nodes and ranks. - Parent Node Widths: The
parent3Childrenandparent2Childrenclasses set fixed widths for parents with 3 or 2 children respectively, making the parent node wider when it has more children. Adjust these width values as needed for your diagram.
Alternative: Using CSS for Dynamic Width (Limited)
If you want to avoid manual width setting, you can target parent nodes via CSS (works in environments that allow custom CSS injection like advanced Notion setups):
/* Target parent nodes based on their class */ .mermaid .node.parent3Children { min-width: 220px; } .mermaid .node.parent2Children { min-width: 160px; }
内容的提问来源于stack exchange,提问作者DH K

