Container Query with Flexbox Direction Switch
Switch a Flexbox layout from column to row direction based on container width using CSS container queries for component-level responsive design.
Detailed Explanation
Flexbox Direction Switch with Container Queries
One of the most common responsive patterns is switching between a vertical (column) and horizontal (row) layout. Container queries let you do this based on the component's actual available space.
The CSS
.flex-container {
container-type: inline-size;
container-name: flex-area;
}
.flex-layout {
display: flex;
flex-direction: column;
gap: 1rem;
}
@container flex-area (min-width: 500px) {
.flex-layout {
flex-direction: row;
align-items: center;
}
}
Column to Row
In narrow containers, items stack vertically, which is natural for small spaces. Once the container reaches 500px, items flow horizontally, making better use of the available width.
Practical Example: User Profile
@container flex-area (min-width: 500px) {
.user-profile {
flex-direction: row;
}
.user-profile .avatar {
width: 80px;
height: 80px;
}
.user-profile .info {
flex: 1;
}
}
A user profile component shows the avatar above the name in narrow contexts but beside it when there is enough room. This is impossible to achieve reliably with viewport-based media queries when the profile widget can appear anywhere.
Why Not Just Use flex-wrap?
flex-wrap: wrap lets items wrap, but it does not give you control over when the layout switches or what changes at the breakpoint. Container queries let you change any CSS property at precise container widths.
Use Case
Use this pattern for profile cards, media objects (image + text), feature sections, or any component that should switch between stacked and side-by-side layouts based on available space.