Sidebar Collapse Pattern with Container Query
Create a sidebar that collapses to icons when its container becomes narrow, using CSS container queries with max-width: 250px for adaptive navigation.
Detailed Explanation
Sidebar Collapse with Container Queries
A common UI pattern is a sidebar that shows full labels when wide and collapses to just icons when space is limited. Container queries make this pattern elegant and self-contained.
The CSS
.sidebar-container {
container-type: inline-size;
container-name: sidebar;
}
.sidebar .label {
display: inline;
}
.sidebar .icon {
margin-right: 0.5rem;
}
@container sidebar (max-width: 250px) {
.sidebar .label {
display: none;
}
.sidebar .icon {
margin-right: 0;
}
}
How It Works
The sidebar wrapper has container-type: inline-size so its children can query its width. When the sidebar container narrows below 250px (for example, when the user drags a resize handle or the main content area expands), text labels disappear and only icons remain.
Advantages Over Media Queries
- The sidebar component is self-contained -- it does not need to know about the viewport.
- If you move the sidebar into a different layout, it still works correctly.
- The collapse point is based on the sidebar's actual width, not the window width.
Adding a Tooltip Fallback
When labels are hidden, consider adding CSS tooltips on hover so users can still discover what each icon means:
@container sidebar (max-width: 250px) {
.sidebar .nav-item:hover::after {
content: attr(data-label);
position: absolute;
/* tooltip positioning */
}
}
Use Case
Use this pattern for dashboard sidebars, file explorers, or any navigation that needs to adapt between expanded and collapsed states based on available space rather than viewport width.