CSS/HTML
Sticky Footer with CSS Flexbox
Create a 'sticky footer' layout that always remains at the bottom of the viewport, even if the main content is short, using CSS Flexbox for robust positioning.
<!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>
</head>
<body class="sticky-footer-body">
<div class="content-wrapper">
<header><h1>Page Header</h1></header>
<main class="main-content-sticky">
<p>This is the main content area. If content is short, the footer will stick to the bottom.</p>
<p>Add more content to make it scrollable and observe the footer at the very end of content.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</main>
</div>
<footer class="sticky-footer">
<p>© 2023 My Sticky Footer</p>
</footer>
</body>
</html>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%; /* Important for html and body to take full height */
font-family: Arial, sans-serif;
}
.sticky-footer-body {
display: flex;
flex-direction: column; /* Stack children vertically */
min-height: 100vh; /* Ensure body takes full viewport height */
}
.content-wrapper {
flex: 1; /* Allows this wrapper to grow and push the footer down */
display: flex; /* For header and main within wrapper */
flex-direction: column;
}
header {
background-color: #f0f0f0;
padding: 20px;
text-align: center;
border-bottom: 1px solid #e0e0e0;
}
.main-content-sticky {
flex: 1; /* Main content grows to fill remaining space */
padding: 20px;
}
.sticky-footer {
background-color: #333;
color: white;
padding: 20px;
text-align: center;
}
</style>
How it works: This snippet implements a sticky footer using Flexbox. The `body` element is set to `display: flex` with `flex-direction: column` to stack its direct children (a content wrapper and the footer) vertically. The `content-wrapper` is given `flex: 1`, allowing it to grow and occupy all available vertical space, effectively pushing the `sticky-footer` to the bottom of the viewport. If the content is long enough to cause scrolling, the footer will appear at the very end of the content, maintaining its 'stickiness' to the bottom of the content flow.