Lesson 8: Flexbox
Flexbox helps you line things up easily.
What you'll learn
- Use
display: flex - Align items with
justify-content - Use
gapfor spacing
Explain like I'm 10
Flexbox is like putting toys in a row with even spacing.
.header { display: flex; gap: 12px; }
Flex container vs flex items
A flex container is an element with display:flex. Its direct children become flex items and are laid out along the main axis.
.row { display: flex; }
.row > * { /* these are flex items */ }
Core properties
Key properties: flex-direction, justify-content, align-items, and gap.
.container { display: flex; flex-direction: row; justify-content: space-between; align-items: center; gap: 12px; }
Wrapping
Use flex-wrap when items should wrap to the next line on small screens.
.wrap { display: flex; flex-wrap: wrap; gap: 12px; }
Practical patterns
Header layout (logo + nav)
<header class="site-header">
<div class="logo">MySite</div>
<nav class="main-nav"><a href="#">Home</a><a href="#">About</a></nav>
<div class="actions"><button>Sign in</button></div>
</header>
/* CSS */
.site-header { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
Card rows
<div class="cards">
<div class="card">...</div>
<div class="card">...</div>
</div>
.cards { display: flex; gap: 16px; flex-wrap: wrap; }
.card { flex: 1 1 220px; /* grow, shrink, base width */ }
Common mistakes & fixes
- Flex on wrong element: Make sure
display:flexis on the container, not a child. - Gap not working:
gapworks on flex container; ensure you're targeting the parent. - Items not wrapping: Add
flex-wrap:wrapto the container.
Practice tasks
- Create a header with a left-aligned logo and centered nav, add a right-aligned button.
- Make a responsive row of cards that wrap on small screens.
- Use
gapto space items instead of margins between children.
Mini challenge
- Make the logo bigger with CSS.
- Add a button on the right.