← Back to all snippets
CSS

Flexbox: Classic Sticky Footer Layout

Ensure your footer always sticks to the bottom of the viewport, even with minimal content, using a robust CSS Flexbox layout for modern web pages, a common layout challenge.

html, body {
  height: 100%; /* Ensures html and body take full viewport height */
  margin: 0;   /* Remove default body margin */
}

body {
  display: flex;
  flex-direction: column; /* Arranges children (header, main, footer) vertically */
}

.header {
  background-color: #f8f9fa;
  padding: 1rem;
  text-align: center;
  border-bottom: 1px solid #e9ecef;
}

.main-content {
  flex: 1; /* This is the key: main content takes all available space */
  padding: 2rem;
  background-color: #fff;
}

.footer {
  background-color: #343a40;
  color: white;
  padding: 1rem;
  text-align: center;
}
How it works: This snippet solves the classic 'sticky footer' problem using Flexbox. By setting `html` and `body` to `height: 100%`, we ensure the `body` can expand to the full viewport height. Then, `body` is set to `display: flex` with `flex-direction: column`, arranging its direct children (header, main-content, footer) vertically. The crucial part is `flex: 1` on `.main-content`. This property makes the main content area grow and shrink to fill all available space between the header and footer, pushing the footer to the bottom of the viewport, regardless of how much content is present in the `.main-content` section.

Need help integrating this into your project?

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

Hire DigitalCodeLabs