Almost all sites consist of main structures called header, content, sidebar and footer. This article will discuss the placement of one of the footer in a react application. Before we start, let's take a look at what the bottom sticky footer is and our react app layout.
What is Sticky Footer
The sticky footer is the structure at the bottom of the screen if the height of the content is less than the height of the screen, otherwise at the bottom of all its content.
Sticky Footer vs Fixed Footer
Do not mix the sticky footer up with a fixed footer, the fixed footer is always placed in the viewport even if the content height is taller than the viewport.
Our React Layout Structure For Placement The Footer
The layout structure is important for deciding which method to use to place the footer. Our react application layout has three main structures, header, content and footer. For simplicity's sake, each component will render its own name in a div container as in the example of code snippet below.
import React from "react"
// Header
export function Header() {
return <div>Header</div>;
}
// Content
export function Content() {
return <div>Content</div>;
}
// Footer
export function Footer() {
// We need to add a className to place the footer
return <div className="footer">Footer</div>;
}
// App.js
import "./App.css";
import Content from "./components/Content";
import Footer from "./components/Footer";
import Header from "./components/Header";
function App() {
return (
<div className="App">
<Header />
<Content />
<Footer />
</div>
);
}
export default App;
3 Ways to Place Sticky Footer in React
Using FlexBox
Flexbox is a powerful way to place any element in an HTML document. You can easily place the footer using the flex column layout and margin-top: auto.
html,
body,
#root {
height: 100%;
}
.App {
min-height: 100%;
display: flex;
flex-direction: column;
}
.footer {
margin-top: auto;
}
Using Grid
The grid system is a great feature in CSS for creating complex structures. It can also be used to place a footer in a react application using the fragment size (1fr) for the content height and auto size for header and footer.
html,
body,
#root {
height: 100%;
}
.App {
min-height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
}
Using CSS calc() Method
If you have a footer with a constant height value, the calc() method can be anohter option for placing a footer in a react application. In the following example, our footer height is 100px.
.App {
min-height: calc(100vh - 100px);
position: relative;
}
.footer {
position: absolute;
bottom: -100px;
height: 100px;
}
Conclusion
In this article, we have covered the placement of a bottom sticky footer in a react application using different methods including the flexbox, grid and CSS calc method, you can choose a method according to your requirements and design layout.
Thank you for reading.