Responsive Sidebar
You'll learn how to build a sidebar that automatically collapses into a vertical layout on mobile screens using flex-direction.
A responsive sidebar is a common pattern where desktop users see content side-by-side (main content + sidebar), but mobile users see it stacked vertically. Flexbox makes this transformation surprisingly simple.
The Core Idea
On larger screens, you want your layout to use flex-direction: row so the sidebar and main content sit next to each other horizontally. On smaller screens, you switch to flex-direction: column so they stack vertically, with the sidebar typically appearing above or below the main content.
Think of it like reading a newspaper: on a wide desk, you can unfold it and see multiple columns side-by-side. On a narrow phone screen, you naturally scroll through one column at a time, top to bottom.
How It Works
.container {
display: flex;
flex-direction: row; /* Side-by-side on desktop */
}
.sidebar {
flex-basis: 250px;
flex-shrink: 0;
}
.main-content {
flex-grow: 1;
}
/* Mobile: stack vertically */
@media (max-width: 768px) {
.container {
flex-direction: column; /* Sidebar on top */
}
.sidebar {
flex-basis: auto; /* Full width when stacked */
}
}
The magic happens in the media query: changing flex-direction from row to column instantly transforms your layout. The sidebar maintains its width on desktop (flex-basis: 250px), while the main content grows to fill remaining space (flex-grow: 1). On mobile, both become full-width blocks.
Key Takeaway: Use flex-direction: row for desktop side-by-side layouts and switch to flex-direction: column in a media query to create mobile-friendly stacked layouts—the foundation of responsive sidebar design.