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.
It should be noted that this is more or less a ‘conditional’ sticky footer since the footer is only sticky when the content is less than the viewport height. If you want a full sticky footer effect, use position: fixed
to set the footer in place. But note that you also have to take into account the area the footer covers by adding some padding to the bottom of the main content area above the footer. Here’s the CSS:
footer {
position: fixed;
width: 100%;
bottom: 0;
box-sizing: border-box;
}
main {
padding-bottom: 140px;
}
Code language: CSS (css)
Demo is below: