A common layout technique, commonly called a sticky footer, was challenging to do in the past with older CSS but is now much easier to accomplish with flexbox. This technique requires that the footer for a given page stays at the bottom of the viewport as long as the content is smaller than the viewport height. When the content exceeds the height of the viewport, the footer behaves like a regular footer, getting pushed down and staying below the content.
The HTML will look something like this:
<body>
<header><h2>Header</h2></header>
<main>
<p>Content goes here...</p>
</main>
<footer><h2>Sticky Footer</h2></footer>
</body>
Code language: HTML, XML (xml)
Notice this uses the <body>
element as the wrapper. If you prefer, you can use an actual wrapper element, but this would require some extra HTML.
The CSS then looks like this:
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
header, footer {
flex-grow: 0;
flex-shrink: 0;
flex-basis: auto;
}
main {
flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;
}
Code language: CSS (css)
The key portions of the CSS are the flex-direction
, and flex-grow
declarations. The flex-shrink
declaration is set to zero, but this probably isn’t required in most cases. Below is an interactive demo. Use the buttons to add or remove extra paragraphs to test the ‘stickiness’ of the footer.