CSS

Implement a Flexible Sticky Footer with CSS Flexbox

Learn to create a robust sticky footer using CSS Flexbox, ensuring the footer always stays at the bottom of the viewport even with minimal content above it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Sticky Footer</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>My Awesome Site</h1>
    </header>
    <main>
        <p>This is the main content area. It will push the footer down.</p>
        <p>Add more content here to see the scrollbar appear.</p>
        <!-- Add more content to test scrolling -->
    </main>
    <footer>
        <p>&copy; 2023 My Site. All rights reserved.</p>
    </footer>
</body>
</html>

html, body {
    margin: 0;
    padding: 0;
    height: 100%; /* Important for Flexbox to take full height */
}

body {
    display: flex;
    flex-direction: column; /* Stack header, main, footer vertically */
    min-height: 100vh; /* Ensure body takes at least full viewport height */
    font-family: sans-serif;
    color: #333;
}

header {
    background-color: #333;
    color: #fff;
    padding: 1rem;
    text-align: center;
}

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

footer {
    background-color: #555;
    color: #fff;
    padding: 1rem;
    text-align: center;
}
How it works: This snippet demonstrates how to create a sticky footer that consistently remains at the bottom of the viewport. By applying `display: flex` and `flex-direction: column` to the `body`, its children (header, main, footer) are stacked vertically. The `min-height: 100vh` on the `body` ensures it occupies at least the full viewport height. The crucial part is `flex-grow: 1` on the `main` element, which allows it to expand and fill any remaining vertical space, pushing the `footer` to the bottom. If content in `main` overflows, the footer will be pushed further down, remaining at the end of the content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs