What is flex-direction column in CSS: Explained Simply
flex-direction: column in CSS sets the main axis of a flex container to run vertically from top to bottom. This means flex items stack in a column instead of a row, making them appear one below the other.How It Works
Imagine you have a row of boxes on a shelf. By default, CSS flex arranges these boxes side by side, like books on a shelf. When you use flex-direction: column, it's like turning the shelf upright so the boxes stack vertically, one on top of the other.
This changes the main axis from horizontal (left to right) to vertical (top to bottom). The flex container then places its child items along this vertical line, making it easy to create vertical layouts without using complicated positioning.
Example
This example shows a flex container with three colored boxes stacked vertically using flex-direction: column.
html, body {
height: 100%;
margin: 0;
}
.container {
display: flex;
flex-direction: column;
height: 200px;
width: 150px;
border: 2px solid #333;
gap: 10px;
padding: 10px;
}
.box {
background-color: #4CAF50;
color: white;
padding: 20px;
text-align: center;
font-weight: bold;
border-radius: 5px;
}
.box:nth-child(2) {
background-color: #2196F3;
}
.box:nth-child(3) {
background-color: #f44336;
}When to Use
Use flex-direction: column when you want to stack items vertically in a flexible container. It's perfect for creating vertical menus, sidebars, or any list of items that should flow from top to bottom.
For example, a navigation menu on a mobile site often uses this to stack links vertically for easy tapping. It also helps when you want to control spacing and alignment of vertical elements without extra CSS tricks.
Key Points
- flex-direction: column stacks flex items vertically.
- The main axis changes from horizontal to vertical.
- Items flow from top to bottom by default.
- Useful for vertical menus, lists, and layouts.
- Works with other flex properties like
justify-contentandalign-itemsto control spacing.
Key Takeaways
flex-direction: column stacks flex items vertically from top to bottom.