Nested flex and baseline alignment
Definition and purpose
Nested flex containers let a component manage its own internal layout while the parent positions that component as a single item. Baseline alignment aligns text baselines across items rather than their top or bottom edges.
Independent inner direction
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; gap: 20px; } #a { display: flex; flex-direction: column; width: 100px; gap: 5px; } #a span { height: 25px; } </style> </head> <body> <div id="p"> <div id="a"> <span id="x">Label</span> <span id="y">Value</span> </div> <div id="b">Action</div> </div> </body></html>The outer row positions the action at x=120; the inner column places Value at y=30.
Syntax and mental model
A flex item can itself have display: flex; its inner direction and gaps are independent. In a row with different text sizes, align-items: baseline aligns the first baselines (when available), with fallback behavior for boxes without a suitable baseline.
Baseline typography
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; align-items: baseline; } #a { font-size: 30px; } #b { font-size: 16px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>Compare the text baselines rather than the tops of the boxes; exact offsets depend on the font.
Common mistakes
Do not assume baseline alignment means equal top coordinates. Avoid forcing a fixed height on text-heavy controls that must grow when text size changes.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Auto margins and visual order. Next lesson: Tracks, lines, cells and areas.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Nested flex and baseline alignment — knowledge check
Five questions on nested flex and baseline alignment.
Can a flex item be a flex container?
Does the outer gap automatically become the inner gap?
Which value aligns first baselines in a flex row?
Must baseline-aligned items have equal top positions?
What is the outer action offset for an inner item 100px wide and a 20px gap?