CSS

CSS Grid Toggleable Sidebar with Content Shift

Implement a responsive layout with a dynamic, toggleable sidebar that expands and collapses, shifting the main content using CSS Grid.

.page-wrapper {
  display: grid;
  grid-template-columns: 250px 1fr; /* Default: Sidebar 250px, Content expands */
  grid-template-areas: "sidebar main";
  min-height: 100vh;
  transition: grid-template-columns 0.3s ease-in-out;
}

.page-wrapper.sidebar-collapsed {
  grid-template-columns: 0 1fr; /* Collapsed: Sidebar 0px, Content expands */
}

.sidebar {
  grid-area: sidebar;
  background-color: #e0f2f7;
  overflow: hidden; /* Hide content when sidebar is 0 width */
  transition: all 0.3s ease-in-out;
}

.main-content {
  grid-area: main;
  background-color: #fff;
  padding: 20px;
}

/* Example of JS to toggle the class:
const toggleSidebar = () => {
  document.querySelector('.page-wrapper').classList.toggle('sidebar-collapsed');
}; */
How it works: This snippet creates a two-column layout using CSS Grid, suitable for a dynamic sidebar. The `.page-wrapper` defines two columns: a fixed-width `250px` for the sidebar and `1fr` for the main content. When the `sidebar-collapsed` class is added, `grid-template-columns` changes the sidebar's width to `0`, causing the main content to expand. `overflow: hidden` on the sidebar ensures its content is not visible when collapsed. A `transition` on `grid-template-columns` provides a smooth animation effect for the expansion/collapse.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs