2024-11-22 web, development, javascript
Sticky Footer
By O. Wolfson
Creating a Sticky Footer in Next.js with Tailwind CSS
Here's how to implement a "sticky footer" in a Next.js project using Tailwind CSS. This layout ensures the footer stays at the bottom of the viewport if there's not enough content to push it down. When content overflows the viewport, the footer naturally moves to the end of the page.
tsx// layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import NavBar from "@/components/NavBar";
import Footer from "@/components/Footer";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<div className="flex flex-col min-h-screen">
<NavBar />
<main className="flex-1 p-4">{children}</main>
<Footer />
</div>
</body>
</html>
);
}
Explanation:
-
The outer
<div>
usesflex flex-col min-h-screen
:flex-col
: stacks its children vertically.min-h-screen
: ensures it is at least as tall as the viewport (100vh).
-
The
<main>
usesflex-1
, which is shorthand for:cssflex-grow: 1; flex-shrink: 1; flex-basis: 0%;
This allows the main content area to expand and take up all remaining vertical space, pushing the footer to the bottom of the page when the content is short.
Note: You could also use
flex-grow
(e.g.,flex-grow
orflex-grow-1
) if you want more granular control, butflex-1
is the more common, idiomatic Tailwind way to handle this.
This pattern works reliably for building sticky footers in responsive layouts with minimal code.