Topic 41 of 62
Flex Direction
Overview
The true superpower of Flexbox is the concept of the 'Main Axis'. When you activate display: flex, the browser draws an invisible straight line through the container. By default, this line goes left-to-right (row). The flex-direction property allows you to instantly rotate this invisible line 90 degrees (column), completely transforming a horizontal navbar into a vertical mobile menu without touching a single line of HTML.
Syntax
css
.container {
display: flex;
/* 1. Row (Default): Left to Right */
flex-direction: row;
/* 2. Column: Top to Bottom (Like normal block elements) */
flex-direction: column;
/* 3. Row Reverse: Right to Left (Swaps the visual order!) */
flex-direction: row-reverse;
/* 4. Column Reverse: Bottom to Top (Swaps the visual order!) */
flex-direction: column-reverse;
}Common Pitfalls
- Forgetting that
flex-directioncompletely re-wires how alignment properties work.justify-contentALWAYS aligns along the Main Axis. If your direction isrow,justify-contentcenters horizontally. But if you change the direction tocolumn,justify-contentnow centers VERTICALLY. The axes rotate with the direction! - Using
row-reverseto change DOM order for accessibility.row-reverseONLY changes the visual painting order on the screen. A screen reader (or keyboard Tab navigation) will still read the HTML in its original top-to-bottom DOM order. Do not use-reverseto fix bad HTML architecture.
Interview Questions
Q:
If a flex container is set to
flex-direction: column, which axis does justify-content operate on?A:
The Vertical axis (Y-axis). justify-content always tracks the Main Axis, which rotated 90 degrees when the direction was set to column.
Real-World Example
Using flex-direction to completely reorganize a layout for Mobile screens.
example
css
/* Default Desktop Layout: Image on the left, Text on the right */
.product-card {
display: flex;
flex-direction: row;
}
/* On Mobile, stack them vertically! */
@media (max-width: 768px) {
.product-card {
/* Image goes on top, text goes on bottom */
flex-direction: column;
}
}Check Your Knowledge
Test your understanding of Flex Direction with these quick questions.