← Back to all snippets
CSS

Flexbox Component with Sticky Header/Footer and Scrollable Body

Create a component with a sticky header or footer using Flexbox, allowing inner content to scroll while crucial elements remain visible at the top or bottom.

.scrollable-component {
  display: flex;
  flex-direction: column;
  height: 300px; /* Fixed height for the component */
  border: 1px solid #ddd;
  overflow: hidden; /* Contains the scrolling */
}

.component-header {
  position: sticky;
  top: 0;
  background-color: #f8f8f8;
  padding: 10px;
  border-bottom: 1px solid #eee;
  z-index: 10;
  flex-shrink: 0; /* Prevent header from shrinking */
}

.component-body {
  flex-grow: 1; /* Allow body to take up remaining space */
  overflow-y: auto; /* Enable vertical scrolling */
  padding: 10px;
}

.component-footer {
  position: sticky;
  bottom: 0;
  background-color: #f8f8f8;
  padding: 10px;
  border-top: 1px solid #eee;
  z-index: 10;
  flex-shrink: 0; /* Prevent footer from shrinking */
}
How it works: This snippet creates a self-contained component with a fixed-height, allowing its internal header and footer to 'stick' to the top and bottom respectively, while the main content area scrolls independently. The outer container uses `display: flex` with `flex-direction: column`. The `component-body` gets `flex-grow: 1` and `overflow-y: auto` to enable scrolling. The `component-header` and `component-footer` elements are made sticky using `position: sticky` and `top: 0` or `bottom: 0`, coupled with `flex-shrink: 0` to maintain their size within the flex container.

Need help integrating this into your project?

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

Hire DigitalCodeLabs