Sometimes, we want to add a fixed header, and footer with scrollable content with CSS.
In this article, we’ll look at how to add a fixed header, and footer with scrollable content with CSS.
How to add a fixed header, and footer with scrollable content with CSS?
To add a fixed header, and footer with scrollable content with CSS, we use flexbox.
For instance, we write
<div class="container">
<header><h1>Header</h1></header>
<div class="body">Body</div>
<footer><h3>Footer</h3></footer>
</div>
to add the elements.
Then we write
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
flex-wrap: nowrap;
}
header {
flex-shrink: 0;
}
.body {
flex-grow: 1;
overflow: auto;
min-height: 2em;
}
footer {
flex-shrink: 0;
}
to make the outer div a flex container with display: flex;
.
We make the flex direction vertical with flex-direction: column;
.
Then we make the inner div fill the height not taken by the header and footer with flex-grow: 1;
.
We make the inner div scrollable when there’s overflowing content with overflow: auto;
.
We stop the header and footer from filling up extra space with flex-shrink: 0;
.