CSS
Creating a Responsive Sticky Footer with Flexbox
Learn how to implement a reliable sticky footer that stays at the bottom of the viewport on short pages and pushes down on longer content using Flexbox.
html, body {
height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
}
.main-content {
flex-grow: 1; /* This makes the content area take up all available space */
}
.footer {
flex-shrink: 0; /* Prevents the footer from shrinking */
background-color: #333;
color: white;
padding: 20px;
text-align: center;
}
/* Example header for context */
.header {
flex-shrink: 0;
background-color: #eee;
padding: 15px;
text-align: center;
}
/* Basic content styling */
.main-content {
padding: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sticky Footer</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="header">
<h1>My Awesome Website</h1>
</header>
<main class="main-content">
<p>This is the main content area. It will push the footer down if there's enough content.</p>
<p>On short pages, the footer will "stick" to the bottom of the viewport.</p>
<!-- Add more content to test scrolling -->
<!-- <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p> -->
</main>
<footer class="footer">
<p>© 2023 My Company. All rights reserved.</p>
</footer>
</body>
</html>
How it works: This snippet demonstrates a robust sticky footer using Flexbox. By setting `html` and `body` to `height: 100%` and `body` to `display: flex; flex-direction: column;`, the main container becomes a Flex column. The `.main-content` area is given `flex-grow: 1` which makes it expand to fill all available vertical space, pushing the `.footer` to the bottom. The `flex-shrink: 0` on header and footer prevents them from shrinking below their intrinsic size.