Flex containers and axes
Definition and purpose
Flexbox lays out direct children along a main axis. The cross axis is perpendicular to it. The axes follow writing mode and flex-direction rather than always being horizontal and vertical.
Horizontal labels
<!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; } #p > div { width: 60px; height: 30px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>B follows A horizontally, with no gap.
Syntax and mental model
display: flex establishes flex layout. In horizontal LTR writing, row starts at the left and column starts at the top. row-reverse and column-reverse reverse the corresponding main direction. Only in-flow direct children become flex items.
Vertical labels
<!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; flex-direction: column; } #p > div { width: 60px; height: 30px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>The main axis now advances downward.
Common mistakes
Do not change reading order by reversing controls. Visual positioning does not normally change DOM or keyboard focus order.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Display contents and hidden boxes. Next lesson: Wrapping and gaps.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Flex containers and axes — knowledge check
Five questions on flex containers and axes.
Which boxes become flex items?
Which property chooses the main direction?
In horizontal LTR, which direction stacks downward?
How is the cross axis related to the main axis?
Does row-reverse normally reorder the DOM?