CSS
Implementing Sticky Elements within a Flex Container
Create sections that stick to the top within a scrollable Flexbox container using `position: sticky`, enhancing user experience for dashboards or tables.
<style>
.scrollable-flex-wrapper {
display: flex;
height: 400px; /* Fixed height for scrollability */
border: 1px solid #ccc;
overflow: hidden; /* Prevent wrapper scroll */
}
.sidebar-fixed {
width: 200px;
background-color: #e6f7ff;
padding: 1rem;
flex-shrink: 0;
overflow-y: auto; /* Enable scrolling for sidebar if content overflows */
}
.main-scroll-area {
flex-grow: 1;
overflow-y: auto; /* Make this area scrollable */
background-color: #ffffff;
position: relative; /* Important for sticky context */
padding: 1rem;
}
.sticky-header {
position: sticky;
top: 0; /* Sticks to the top of its scrolling parent */
background-color: #a7d9e8;
padding: 0.8rem 1rem;
border-bottom: 1px solid #6cb2d2;
z-index: 10;
margin: -1rem; /* Adjust for parent padding */
margin-bottom: 1rem;
}
.content-section {
padding: 1rem 0;
border-bottom: 1px dashed #eee;
}
.content-section:last-child {
border-bottom: none;
padding-bottom: 50px; /* Add extra padding to demonstrate scroll */
}
</style>
<div class="scrollable-flex-wrapper">
<div class="sidebar-fixed">
<h3>Navigation</h3>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<li>Link 5</li>
<li>Link 6</li>
<li>Link 7</li>
<li>Link 8</li>
<li>Link 9</li>
<li>Link 10</li>
<li>Link 11</li>
<li>Link 12</li>
</ul>
</div>
<div class="main-scroll-area">
<div class="sticky-header">Section Header (Sticky)</div>
<p>Scroll down to see the header stick.</p>
<div class="content-section">Long content section 1.</div>
<div class="content-section">Long content section 2.</div>
<div class="content-section">Long content section 3.</div>
<div class="content-section">Long content section 4.</div>
<div class="content-section">Long content section 5.</div>
<div class="content-section">Long content section 6.</div>
<div class="content-section">Long content section 7.</div>
<div class="content-section">Long content section 8.</div>
<div class="content-section">Long content section 9.</div>
<div class="content-section">Long content section 10.</div>
</div>
</div>
How it works: This snippet demonstrates how to achieve sticky elements within a specific scrollable region when working with a Flexbox layout. The `.main-scroll-area` is set as the scrolling container using `overflow-y: auto` and `position: relative` (to establish a positioning context for the sticky element). Inside this, `.sticky-header` uses `position: sticky` and `top: 0` to stick to the top of its scrolling parent as the user scrolls. This pattern is ideal for internal headers, sub-navigation, or action bars within a defined scroll area, offering a more engaging user experience.