Grid versus flex and composition
Definition and purpose
Choose Flexbox when the main relationship is along one axis, such as a toolbar. Choose Grid when rows and columns need coordinated placement, such as a card matrix. Real interfaces often use both at different levels.
Grid shell, flex toolbar
<!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: grid; grid-template-columns: 100px 190px; gap: 10px; } #a { grid-column: 1 / 3; display: flex; justify-content: space-between; } #a span { width: 50px; } </style> </head> <body> <div id="p"> <div id="a"> <span id="x">Title</span> <span id="y">Edit</span> </div> <div id="b">Details</div> <div id="c">Status</div> </div> </body></html>The toolbar spans the grid while its controls occupy opposite ends.
Syntax and mental model
A grid item can establish flex layout for its children: the outer grid assigns its area, while the inner flex row aligns controls. Conversely a flex item may contain a grid. Decide the outer sizing constraints first, then the inner alignment and content behavior.
Flex shell, grid details
<!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: 10px; } #a { flex: 0 0 180px; display: grid; grid-template-columns: 80px 90px; gap: 10px; } #b, #c { flex: 0 0 50px; } </style> </head> <body> <div id="p"> <div id="a"> <span id="x">Title</span> <span id="y">Edit</span> </div> <div id="b">Details</div> <div id="c">Status</div> </div> </body></html>The flex line distributes components; the nested grid aligns its fields.
Common mistakes
Do not force a wrapping flex layout into strict shared columns by assigning brittle item widths. Do not choose grid solely because a component has several children. Keep semantic source order and test with more content.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Grid alignment and subgrid. Next lesson: Fluid and mobile-first layouts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Grid versus flex and composition — knowledge check
Five questions on grid versus flex and composition.
Which layout is a natural fit for a single-axis toolbar?
Which model coordinates rows and columns?
Can a grid item be a flex container?
Why not use wrapping flex for precise shared columns across lines?
What should remain meaningful when switching layouts?