Layout Engine
Layout Engine
The layout layer turns a styled DOM into geometry: a box tree, then fragments with sizes and positions. It is the stage after computed styles, and its outputs are plain Python objects you can inspect.
From DOM to Box Tree
build_box_tree() produces a BoxRoot of BoxNode entries from a styled document, classifying each element’s display model via classify_display() against the Display enumeration. ComputedStyle and EdgeSizes carry the per-box style and box-model measurements.
Block Layout
layout_block_tree() performs block-level layout over the box tree, producing a FragmentRoot containing BlockFragment entries with resolved geometry.
Inline Layout
Inline content is shaped into ShapedRun and InlineTextFragment pieces, assembled into LineFragment lines via layout_inline_fragments() and flush_inline_run().
Pagination
paginate_fragments() splits fragment output into PageFragment pages, honouring BreakHints, with PageMarginBoxes modelling page-margin areas and flush_page() finalizing each page.
Tips and Best Practices
- Resolve computed styles before layout — the box tree derives from styled elements
- Inspect
EdgeSizeswhen box dimensions look wrong; margins and padding resolve there - Keep the box tree and fragment tree distinct in your mental model: boxes describe structure, fragments describe placed geometry
Common Issues
| Issue | Cause | Fix |
|---|---|---|
| Empty fragment output | Layout run on an unstyled or empty tree | Attach stylesheets and content first |
| Unexpected display classification | Element’s computed display differs from assumption | Check classify_display() result for the box |
| Page breaks in odd places | Break hints not set | Provide BreakHints to paginate_fragments() |
FAQ
What is the difference between a box and a fragment?
Boxes (BoxNode) describe the layout structure derived from styles; fragments (BlockFragment, LineFragment) are the placed results with geometry.
Does the engine handle pagination?
Yes — paginate_fragments() produces PageFragment pages with margin boxes.
Where do text runs come from?
Inline content is shaped into ShapedRun objects and assembled into LineFragment lines.
API Reference Summary
| Class/Method | Description |
|---|---|
build_box_tree | Derive the box tree from a styled DOM |
layout_block_tree | Run block layout over the box tree |
layout_inline_fragments | Assemble inline content into lines |
paginate_fragments | Split fragments into pages |
BoxNode | One box in the layout structure |
PageFragment | One laid-out page |