Back to course

Lesson 64: Flexbox Practical: Creating a Sticky Footer and Navbar

CSS Mastery: From Zero to Hero in 100 Lessons

64. Flexbox Practical: Creating a Sticky Footer and Navbar

Flexbox is excellent for structuring large parts of a page. Here we solve two classic layout problems: the sticky footer and the full-height nav.

1. The Sticky Footer Problem

The goal is to have the footer stick to the bottom of the viewport, even if the content is too short to fill the screen.

Solution: Turn the <body> into a column-based flex container.

css html, body { height: 100%; margin: 0; }

body { display: flex; flex-direction: column; /* Main axis is vertical */ }

.main-content { /* This is the magic: it grows to take up all remaining vertical space */ flex-grow: 1; }

footer { flex-shrink: 0; /* Ensures footer does not shrink */ padding: 20px; background: #333; color: white; }

2. Horizontal Navbar Alignment

Centering items, pushing a logo to one side, and distributing links is trivial with Flexbox.

css .navbar { display: flex; justify-content: space-between; /* Pushes logo to left, links to right / align-items: center; / Vertically center items */ padding: 10px; }

.logo { /* Prevent logo from being manipulated */ flex-shrink: 0; }

.nav-links { display: flex; /* Links inside the nav-links container will flow horizontally / gap: 15px; / Spacing between links (Lesson 65) */ }