I have a footer at the bottom of my page, where I want the following:
- Be all the way at the bottom after the content of the page
- Be at the bottom of the screen if there’s not enough content to fill the page
- I am using React with Material UI
I’ve found some guides using the height of the footer as a buffer, but that requires hardcoding that height. (Such as where I got the picture: link.)
I’ve also found guides using flexbox, and while that seems easy enough, I can’t get it to work within react. I’ve tried this example.
Code:
import type { Metadata } from "next";
import "./globals.css";
import { AppRouterCacheProvider } from "@mui/material-nextjs/v13-appRouter";
import Box from "@mui/material/Box";
import { AppBar, Typography } from "@mui/material";
export const metadata: Metadata = {
title: "Footer example",
description: "How can footers be hard?"
};
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="en">
<body>
<AppRouterCacheProvider>
<Box
sx={{
height: "100%",
display: "flex",
flexDirection: "column"
}}
>
<AppBar sx={{ height: "80px" }} />
<Box
sx={{
flexGrow: 1,
flexShrink: 0,
flexBasis: "auto"
}}
>
{children}
</Box>
<Box
sx={{
backgroundColor: "lightblue",
flexShrink: 0
}}
>
<Typography>Example footer!</Typography>
</Box>
</Box>
</AppRouterCacheProvider>
</body>
</html>
);
}
Any idea what I’m doing wrong here?
3
It’s just a small change, since you want your footer to be at the bottom at the very least, and then come after content, adding minHeight: 100vh
would work in your flexbox
.
<Box sx={{
minHeight: "100vh",
display: "flex",
flexDirection: "column",
}}
>
//Your Code
Note:- Be careful that 100vh
might give additional scroll in some cases, so just update the height to 98vh
or 99vh
but it should work fine in most of the cases.
Flexbox layout: The column flex layout ensures the footer is either at the bottom of the page or follows the content when it’s long enough.
for this we need =>
<Box sx={{
minHeight: "100vh",
display: "flex",
flexDirection: "column",
}}
>
<AppBar sx={{ height: "80px" }} />
<Box sx={{
flexGrow: 1,
flexShrink: 0,
flexBasis: "auto",
}}
>
{children}
</Box>
{/* Footer */}
<Box
sx={{
backgroundColor: "lightblue",
flexShrink: 0,
}}
>
<Typography>Example footer!</Typography>
</Box>
</Box>