Flexbox Basics
Learn the core Flexbox model: flex container, flex items, main axis, cross axis, and the most-used flex properties.
Overview
Key Points
- •display: flex on the parent turns its direct children into flex items
- •Default flex-direction is row (left to right)
- •justify-content controls spacing along the main axis
- •align-items controls alignment along the cross axis
- •gap: 16px adds space between all flex items (no negative margins needed)
- •flex-wrap: wrap allows items to flow to the next line
Examples
Horizontal navigation with justify-content
.navbar {
display: flex;
justify-content: space-between; /* logo left, links right */
align-items: center; /* vertically centered */
padding: 0 24px;
height: 60px;
}justify-content: space-between puts the first item at the left edge and the last at the right edge.
Centering with flexbox the most common use
.center-container {
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
height: 100vh;
}This 5-line snippet centers any content perfectly something that was painful before Flexbox.
Card row with gap and wrap
.card-grid {
display: flex;
flex-wrap: wrap; /* cards wrap to next line */
gap: 24px; /* space between cards */
}
.card {
flex: 1 1 280px; /* grow, shrink, min-width 280px */
}"flex: 1 1 280px" means the card can grow and shrink but starts at 280px wide.
Common Mistakes
- Setting display: flex on the child instead of the parent
- Confusing justify-content (main axis) with align-items (cross axis)
- Forgetting gap using margin hacks instead
Note
To vertically center any element inside a full-height container: display: flex; align-items: center; on the parent. This works even without setting height on the child.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4