Responsive Sidebar with Flexbox

Build a responsive sidebar layout using Flexbox. The sidebar has a fixed width while the main content fills the remaining space, collapsing on small screens.

Responsive Patterns

Detailed Explanation

Fixed Sidebar with Flexible Content

A sidebar layout is one of the most common web patterns: a fixed-width navigation panel alongside a flexible main content area. Flexbox handles this elegantly.

CSS Code

.layout {
  display: flex;
  gap: 24px;
  min-height: 100vh;
}

.sidebar {
  flex: 0 0 250px;
}

.main {
  flex: 1;
  min-width: 0;
}

How It Works

  • Sidebar: flex: 0 0 250px means the sidebar does not grow (flex-grow: 0), does not shrink (flex-shrink: 0), and has a fixed basis of 250px. It stays exactly 250px wide regardless of container size.
  • Main content: flex: 1 means it grows to fill all remaining space. min-width: 0 prevents content overflow — without it, long text or wide elements can push the layout beyond the viewport.

Making It Responsive

@media (max-width: 768px) {
  .layout {
    flex-direction: column;
  }

  .sidebar {
    flex-basis: auto;
  }
}

On small screens, switching to flex-direction: column stacks the sidebar above (or below) the main content. Setting flex-basis: auto allows the sidebar to take its natural height.

Why min-width: 0 Matters

By default, flex items have min-width: auto, which prevents them from shrinking below their content's minimum width. This can cause overflow when content contains long URLs, code blocks, or wide tables. Setting min-width: 0 allows the flex item to shrink past its content width, enabling proper text wrapping and overflow handling.

Double Sidebar

For a three-column layout with sidebars on both sides:

.left-sidebar { flex: 0 0 200px; }
.main { flex: 1; min-width: 0; }
.right-sidebar { flex: 0 0 250px; }

Use Case

Use this layout for admin dashboards, documentation sites, email clients, or any application with persistent navigation. The fixed sidebar ensures navigation is always accessible while the main content area adapts to the available width.

Try It — Flexbox Playground

Open full tool