I found this CodePen solution for a sticky footer in a CSS Grid layout, but it has two problems for me:
- It is kinda ugly with
min-height: 100%
andheight: 100%
- It only works with two elements in the body (a div and a footer)
I need something that works with this HTML structure:
<body>
<nav>Some navigation buttons</nav>
<main>The content</main>
<footer>Copyrights and stuff</footer>
</body>
I don't really want to pack the <nav>
and the <main>
into a <div>
, and I would love to do this in pure CSS.
// Not required!
// This is just to demo functionality.
$("#add").on("click", function() {
$("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo(".content");
});
html {
height: 100%;
}
body {
min-height: 100%;
display: grid;
grid-template-rows: 1fr auto;
}
.content {
padding: 20px;
}
.footer {
grid-row-start: 2;
grid-row-end: 3;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font: 16px Sans-Serif;
}
h1 {
margin: 0 0 20px 0;
}
p {
margin: 0 0 20px 0;
}
.footer {
background: #42A5F5;
color: white;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<h1>Sticky Footer with Grid</h1>
<p><button id="add">Add Content</button></p>
</div>
<footer class="footer">
Footer
</footer>
Here is a CSS Grid solution, but it's far better using a class for the target.
Using grid-areas this will be very straightforward:
https://codepen.io/whisher/pen/vWmvQw
Sticky footer is achieved with a single line of CSS, namely:
min-height: 100vh
.Example below:
The trick is to use:
min-height: 100vh; grid-template-rows: auto auto 1fr;
with...align-self: end;
for the footer.If we add left/right margins, place the
<nav>
in a header, add a margin for the footer content and assume another grid for the main content:This has elegant simplicity that previous solutions lack.
With evergreen browsers there is no need to complicate matters.
Previous answers are not as maintainable. Pitfalls include:
CSS Grid is a great tool for putting together complex layouts.
But you're looking for a simple one-column grid, with three rows, and the footer pinned to the bottom of the container.
I would suggest that flexbox is a simpler and more efficient solution in this case. (You can always use Grid within each flex item.)
revised codepen
For more information about flex auto margins, see this post: