CSS

Implementing a Sticky Footer with Flexbox or CSS Grid

Ensure your footer always stays at the bottom of the viewport, even with minimal content, by using Flexbox or CSS Grid for a robust full-height page layout solution.

/* HTML Structure Example: */
/* <body class="flex-layout"> or <body class="grid-layout">
 *   <header>...</header>
 *   <main>...</main>
 *   <footer>...</footer>
 * </body>
 */

/* Flexbox Sticky Footer */
.flex-layout {
  display: flex;
  flex-direction: column; /* Stack children vertically */
  min-height: 100vh;     /* Ensure body takes full viewport height */
}

.flex-layout main {
  flex-grow: 1; /* Main content takes up all available space */
}

.flex-layout header,
.flex-layout footer {
  /* Your header and footer styles */
  padding: 1rem;
  background-color: #eee;
  text-align: center;
}

/* CSS Grid Sticky Footer */
.grid-layout {
  display: grid;
  /* Define rows: auto height for header, 1fr for main (takes remaining space), auto for footer */
  grid-template-rows: auto 1fr auto;
  min-height: 100vh; /* Ensure body takes full viewport height */
}

.grid-layout header {
  grid-row: 1;
  /* Your header styles */
  padding: 1rem;
  background-color: #eee;
  text-align: center;
}

.grid-layout main {
  grid-row: 2;
  /* Your main content styles */
  padding: 1.5rem;
}

.grid-layout footer {
  grid-row: 3;
  /* Your footer styles */
  padding: 1rem;
  background-color: #eee;
  text-align: center;
}
How it works: This snippet solves the common 'sticky footer' problem, ensuring your footer always remains at the bottom of the viewport, regardless of how much content is on the page. The Flexbox method uses `display: flex;` and `flex-direction: column;` on the `body` (or main container) and sets `flex-grow: 1;` on the main content area, pushing the footer down. The CSS Grid method achieves the same by defining `grid-template-rows: auto 1fr auto;`, which allocates minimal height to the header and footer (`auto`) and gives all remaining space (`1fr`) to the main content area. Both methods require `min-height: 100vh;` on the container to ensure it fills the viewport.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs