CSS

Implementing a Sticky Flexbox Sidebar with Independent Scroll Area

Create a layout where a sidebar remains fixed in view while the main content area scrolls independently, all within a responsive Flexbox container.

body {
    margin: 0;
    font-family: sans-serif;
    height: 100vh; /* Make body fill viewport height */
    display: flex; /* Establish flex context for direct children */
    overflow: hidden; /* Prevent body scroll if content overflows */
}
.sidebar {
    flex: 0 0 250px; /* Fixed width sidebar */
    background-color: #333;
    color: white;
    padding: 1rem;
    overflow-y: auto; /* Enable sidebar content to scroll */
    height: 100%; /* Ensure sidebar takes full height */
    box-sizing: border-box; /* Include padding in height */
}
.main-content-wrapper {
    flex: 1; /* Main content takes remaining space */
    display: flex;
    flex-direction: column; /* Allows internal header/scrollable content */
    min-width: 0; /* Important for flex items to shrink */
}
.main-header {
    background-color: #f0f0f0;
    padding: 1rem;
    text-align: center;
    border-bottom: 1px solid #ccc;
}
.main-scrollable-area {
    flex: 1; /* Takes remaining space in column */
    overflow-y: auto; /* Enable main content to scroll */
    padding: 1rem;
    background-color: #fff;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    body {
        flex-direction: column; /* Stack sidebar and main content vertically */
    }
    .sidebar {
        flex: 0 0 auto; /* Allow sidebar to take natural height */
        height: auto;
        max-height: 200px; /* Limit sidebar height on mobile */
        border-bottom: 1px solid #555;
    }
}
How it works: This snippet creates a two-column layout where a sidebar remains sticky on the left, and the main content area scrolls independently. The `body` acts as the main flex container. The `.sidebar` has a fixed width and `overflow-y: auto` to allow its content to scroll. The `.main-content-wrapper` takes the remaining space and itself is a flex container, ensuring its internal `main-scrollable-area` fills the available height and can scroll independently. Media queries adapt the layout for smaller screens, stacking the sidebar above the main content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs