dev-resources.site
for different kinds of informations.
Keeping the Footer at the Bottom with CSS-Grid
At some point in a project, one gets annoyed by the footer hovering right under the header, because there is no content yet to fill up the space. There also may be some really short pages (like the 404), which might not be long enough to fill the whole browser.
Keeping the footer at the browser's bottom just got a little bit easier with CSS-Grid. It's possible to go with some CSS-trickery, Flexbox or JS, but the Grid-solution is the most elegant and simple in my opinion.
Please note that this is only supported in modern browsers, as of this writing. The good thing is, that this method won't break anything for older browsers.
The HTML-Structure will be as follows:
<html>
<body>
<article>
<header>
</header>
<main>
</main>
<footer>
</footer>
</article>
</body>
</html>
This is probably a bit simplified in comparison to some real-world-projects. It's important to keep the main content-area (main) and the footer (footer) in the same parent-element.
html, body {
width: 100%;
height: 100%;
}
article {
min-height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: 100%;
}
The important bit is the "grid-template-rows"-property. Here we tell the browser, that we want the first child-element of "article" to be just as high as it naturally is ("auto"). The second should be one fr high, which means it will get as high as possible, since there's no other fr-item in there. The third child will be of natural height. again.
Don't forget to set the html- and body-elements to be of 100% height, or else your grid-container won't fill up the entire browser.
Here's the working example on CodePen.
In case you didn't know: CSS-Grid is now supported on every modern browser. It's a convenient way to define page-layouts and so much more. Go check out Wes Bos' free course on the topic.
EDIT:
You can achieve the same thing with Flexbox. If you need the feature today (Jan 2018), this would be a wider supported way. Check out Dominik Weber's article "Keeping the footer at the bottom with CSS Flexbox"
UPDATE:
Firefox 52 supports Grid, but it's buggy, especially for this case. The elements are not keeping their natural heights. So if you need to support FF52, use the Flexbox-Solution.
Featured ones: