# How the 4px Grid System Shapes Layout in Diagram-Design

> Discover how the 4px grid system in Diagram-Design ensures pixel-perfect alignment and predictable visual rhythm by making all values divisible by four. Learn to create consistent layouts.

- Repository: [Cathryn Lavery/diagram-design](https://github.com/cathrynlavery/diagram-design)
- Tags: deep-dive
- Published: 2026-08-18

---

**The 4px grid system in Diagram-Design enforces a hard rule requiring every coordinate, dimension, and spacing value to be divisible by four, ensuring pixel-perfect alignment and predictable visual rhythm across all diagram types.**

The cathrynlavery/diagram-design repository implements a strict baseline grid architecture that governs every measurable property in a diagram. This system eliminates sub-pixel misalignment while providing a mathematical foundation for auto-layout algorithms and cross-type consistency.

## Core Principles of the 4px Grid

### The Hard Rule Definition

According to [`skills/diagram-design/SKILL.md`](https://github.com/cathrynlavery/diagram-design/blob/main/skills/diagram-design/SKILL.md), the grid system operates as an absolute constraint: **all numeric values**—including font sizes, node widths and heights, x/y coordinates, gaps, paddings, and border radii—must be multiples of 4 (lines 38-53). The [`style-guide.md`](https://github.com/cathrynlavery/diagram-design/blob/main/style-guide.md) file formalizes this by declaring the `grid` token with a value of `4`, explicitly stating that "every coord, size, and gap is divisible by 4 (hard rule)" (line 103).

Unlike relative grids that scale with viewport size, this system uses a fixed 4px unit. The documentation provides a quick validation check: if any coordinate ends in 1, 2, 3, 5, 6, 7, or 9, it violates the standard and must be corrected (SKILL.md lines 55-56).

### Universal Application Across Diagram Types

The 4px grid applies uniformly across all diagram variants. In treemap layouts, cell edges snap to the 4px grid and maintain a strict 4px gutter between cells ([`type-treemap.md`](https://github.com/cathrynlavery/diagram-design/blob/main/type-treemap.md) lines 12-15). Sequence diagrams enforce vertical spacing of at least 24px between elements, which aligns perfectly with the grid system ([`type-sequence.md`](https://github.com/cathrynlavery/diagram-design/blob/main/type-sequence.md) lines 78-80). This universality ensures that switching a diagram from a treemap view to a high-level architectural view preserves spacing relationships without manual recalculation.

## Impact on Layout and Spacing

### Predictable Visual Rhythm

Because the grid restricts values to multiples of four, default spacing tokens naturally align to the lattice. Common gaps such as **20px**, **24px**, and **32px** between nodes all land on exact grid lines, creating consistent negative space that prevents the "hand-dragged" appearance of arbitrary positioning (SKILL.md lines 48-50). This constraint simplifies design decisions—instead of debating whether to use 21px or 22px, the system authorizes only 20px or 24px.

### Orthogonal Connector Geometry

The hard grid enables cleaner connector routing in auto-layout algorithms. By snapping coordinates to the nearest multiple of four using the formula `round(coord / 4) * 4`, elbow connectors maintain perfect 90-degree angles without sub-pixel anti-aliasing artifacts. This mathematical predictability guarantees that lines intersect precisely at grid points rather than floating between pixels.

## Implementation Examples

### Snapping Coordinates to the Grid

The [`verify-geometry.py`](https://github.com/cathrynlavery/diagram-design/blob/main/verify-geometry.py) script uses standard rounding arithmetic to enforce compliance. You can implement the same snapping logic in Python:

```python
def snap_to_grid(value: int, grid: int = 4) -> int:
    """Round `value` to the nearest multiple of `grid`."""
    return round(value / grid) * grid

# Example: raw coordinates from a draw.io import

raw_x, raw_y = 237, 103
x, y = snap_to_grid(raw_x), snap_to_grid(raw_y)
print(x, y)   # → 236 104

```

### SVG Output Compliance

When generating SVG markup, every attribute must respect the grid. The following snippet demonstrates a compliant node where position, dimensions, and corner radius all align to 4px increments:

```svg
<!-- Node positioned on the 4px grid -->
<rect x="120" y="80" width="96" height="96" rx="4"
      fill="#ffffff" stroke="#2d3142" stroke-width="1"/>
<!-- Text inside the node (font size 12px, also a multiple of 4) -->
<text x="168" y="108" font-size="12"
      font-family="Geist, sans-serif" text-anchor="middle">
  Service A
</text>

```

All coordinates (`x="120"`, `y="80"`), dimensions (`width="96"`), and corner radius (`rx="4"`) satisfy the divisibility requirement.

### Treemap Layout Generation

When calculating treemap cells with gutters, the grid ensures both cell edges and spacing align perfectly:

```python
cell_width = 200            # divisible by 4

gutter = 4                  # 4px gutter between cells

for col in range(cols):
    for row in range(rows):
        x = snap_to_grid(col * (cell_width + gutter))
        y = snap_to_grid(row * (cell_width + gutter))
        draw_cell(x, y, cell_width, cell_width)

```

This matches the specification in [`type-treemap.md`](https://github.com/cathrynlavery/diagram-design/blob/main/type-treemap.md) (lines 12-15), where cell edges and gutters must align to the 4px grid.

## Automated Verification

The repository includes [`scripts/verify-geometry.py`](https://github.com/cathrynlavery/diagram-design/blob/main/scripts/verify-geometry.py) to detect violations programmatically. This script inspects every coordinate in a generated diagram and flags any value that does not end in 0, 4, 8, or 2 (SKILL.md lines 58-60). Running this verification as part of a CI pipeline prevents layout drift and maintains the visual integrity defined in the style guide.

## Summary

- **Hard rule enforcement**: Every dimension, coordinate, and spacing value must be divisible by 4 according to [`SKILL.md`](https://github.com/cathrynlavery/diagram-design/blob/main/SKILL.md) and [`style-guide.md`](https://github.com/cathrynlavery/diagram-design/blob/main/style-guide.md).
- **Universal scope**: The grid applies to all diagram types including treemaps, sequence diagrams, and architectural views.
- **Mathematical consistency**: Coordinate snapping uses `round(value / 4) * 4` to maintain orthogonal geometry.
- **Automated validation**: The [`verify-geometry.py`](https://github.com/cathrynlavery/diagram-design/blob/main/verify-geometry.py) script checks compliance to catch misalignment errors before deployment.
- **Visual harmony**: Fixed 4px units eliminate sub-pixel rendering issues and create predictable spacing relationships.

## Frequently Asked Questions

### What happens if a coordinate violates the 4px grid rule?

Any coordinate ending in 1, 2, 3, 5, 6, 7, or 9 is automatically flagged as an error by the [`verify-geometry.py`](https://github.com/cathrynlavery/diagram-design/blob/main/verify-geometry.py) script. According to the documentation in [`SKILL.md`](https://github.com/cathrynlavery/diagram-design/blob/main/SKILL.md), these values must be fixed to the nearest multiple of 4, either manually or through automated snapping algorithms.

### Does the 4px grid apply to typography in diagram-design?

Yes, font sizes must also be multiples of 4. The specification explicitly lists font sizes alongside coordinates and dimensions as values governed by the grid system (SKILL.md lines 38-53). For example, 12px and 16px type sizes are compliant, while 11px or 13px are not.

### How does the grid system handle different screen resolutions or scaling?

The 4px grid is absolute and not relative to viewport size. This fixed-unit approach ensures that diagrams render with identical spatial relationships regardless of display scaling factor, preventing the fractional pixel misalignment that occurs with relative percentage-based layouts.

### Can I change the grid base unit from 4px to 8px or another value?

While the [`style-guide.md`](https://github.com/cathrynlavery/diagram-design/blob/main/style-guide.md) declares the `grid` token as `4` (line 103), changing this value would require updating the entire design system including spacing tokens, verification scripts, and all diagram type specifications. The repository treats 4px as a fundamental constant rather than a configurable variable.