Flexbox algorithm
Flexbox is a one-dimensional layout method for arranging items along a main axis with flexible sizing.Flexbox excels at distributing space and aligning items within a container, even when their sizes are unknown or dynamic.
Main and cross axis
Flexbox layouts are oriented along two perpendicular axes:- Main axis
- Cross axis
The primary axis along which flex items are laid out. Direction is determined by Main axis properties:
flex-direction.justify-content- Aligns items along main axisflex-grow- Controls growth along main axisflex-shrink- Controls shrinking along main axisflex-basis- Sets initial size along main axis
Flex direction
Theflex-direction property establishes the main axis:
row
Main axis runs left to right (or right to left in RTL languages). Items are arranged horizontally.
row-reverse
Main axis runs right to left (or left to right in RTL languages). Items are arranged horizontally in reverse order.
column
Main axis runs top to bottom. Items are arranged vertically.
column-reverse
Main axis runs bottom to top. Items are arranged vertically in reverse order.
Flex basis
Theflex-basis property sets the initial size of a flex item before space distribution:
Determine flex basis
Start with the value of
flex-basis. If set to auto, use the item’s content size or explicit width/height.Setting
flex-basis: 0 with flex-grow: 1 distributes space based purely on the grow factor, ignoring content size.Flex grow
Theflex-grow property controls how flex items expand to fill available space:
Distribute proportionally
Each item receives additional space proportional to its
flex-grow value divided by the total.Flex shrink
Theflex-shrink property controls how flex items shrink when the container is too small:
Calculate overflow
Determine how much the items overflow the container when laid out at flex-basis size.
Calculate scaled shrink factors
Multiply each item’s
flex-shrink value by its flex-basis to get its scaled factor.Distribute proportionally
Each item shrinks proportionally to its scaled shrink factor divided by the total.
Complete flexbox layout algorithm
The full flexbox layout algorithm follows these steps:Generate flex items
Determine which children become flex items. Absolutely positioned children and text nodes are handled differently.
Calculate flex-basis
Determine the hypothetical main size of each flex item based on
flex-basis, content size, and constraints.Collect items into lines
If
flex-wrap is enabled, break items into multiple lines based on container size.Resolve flexible lengths
Apply
flex-grow or flex-shrink to distribute free space or absorb overflow.Determine cross size
Calculate each item’s cross size based on content,
align-items, and align-self.The flexbox specification defines a precise algorithm with many edge cases. Production implementations must handle nested flex containers, baseline alignment, and interactions with other layout modes.
Grid algorithm
CSS Grid is a two-dimensional layout system that divides space into rows and columns.Grid track sizing
Grid tracks (rows and columns) are sized using a sophisticated algorithm that handles fixed, flexible, and content-based sizing:- Fixed sizing
- Flexible sizing (fr)
- Content-based sizing
- Minmax function
Tracks with explicit sizes in absolute units.
Track sizing algorithm
The grid track sizing algorithm resolves track sizes through multiple passes:Resolve intrinsic sizes
For content-based tracks, measure min-content and max-content sizes of items in the track.
Maximize tracks
Distribute space to grow tracks up to their growth limits, starting with the smallest tracks.
Expand flexible tracks
If there are
fr units, distribute remaining space proportionally to their flex factors.Grid item placement
Items are placed into the grid using automatic or explicit positioning:- Explicit placement
- Named areas
- Auto placement
Use line numbers or named lines to position items.
Item spanning
Grid items can span multiple rows or columns:Resolve auto-placement
For auto-placed spanning items, find the first position where the item fits without overlapping.
Grid gaps
Thegap property (formerly grid-gap) adds spacing between tracks:
Gaps are added between tracks, not at the edges. A grid with 3 columns and a 10px gap has 2 gaps totaling 20px.
Implementation considerations
When implementing flexbox and grid algorithms:Measure content sizes
Efficiently measure min-content and max-content sizes by performing layout with different constraints.
Handle circular dependencies
Detect and resolve circular dependencies where item size depends on container size which depends on item size.
Optimize for common cases
Fast-path simple layouts (all fixed sizes, no spanning) before running the full algorithm.
Cache intermediate results
Store track sizes and item placements to avoid recalculation when only some items change.
Project checkpoint: Implement flexbox and grid layout algorithms in your browser engine. Handle all flex properties (basis, grow, shrink) and grid features (track sizing, placement, spanning). Test with complex real-world layouts and measure algorithm performance.