CSS
Creating Fluid Vertical Sections with Flexbox flex-grow
Learn to build flexible layouts where content sections automatically expand or shrink to fill available vertical space using Flexbox's flex-grow property for dynamic sizing.
.container {
display: flex;
flex-direction: column;
height: 100vh; /* Or a fixed height for the container */
}
.header, .footer {
flex-shrink: 0; /* Prevent header/footer from shrinking */
padding: 15px;
background-color: #f0f0f0;
text-align: center;
}
.content-area-1 {
flex-grow: 1; /* This area takes up remaining space */
overflow-y: auto; /* If content overflows, scroll it */
padding: 20px;
background-color: #e6f7ff;
}
.content-area-2 {
flex-grow: 2; /* This area takes up twice as much remaining space as area 1 */
overflow-y: auto;
padding: 20px;
background-color: #fff0e6;
}
<!-- HTML for context -->
<div class="container">
<div class="header">Page Header</div>
<div class="content-area-1">
<h2>Section One</h2>
<p>This section will grow to fill available vertical space. It has a flex-grow value of 1.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="content-area-2">
<h2>Section Two</h2>
<p>This section will grow twice as much as Section One, with a flex-grow value of 2.</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<div class="footer">Page Footer</div>
</div>
How it works: This snippet creates a vertical Flexbox container (`flex-direction: column`) where header and footer elements have `flex-shrink: 0` to maintain their size. The `.content-area-1` and `.content-area-2` elements use `flex-grow` to distribute the remaining vertical space. `.content-area-2` will take up twice as much space as `.content-area-1` because of its `flex-grow: 2` value, ensuring a responsive distribution of height. `overflow-y: auto` is added for scrollability if content exceeds its allocated area, preventing the entire page from scrolling unnecessarily.