Flexbox Fundamentals
Learning Objectives
- Understand flex containers and flex items.
- Understand main and cross axes.
- Use flex-direction, justify-content and align-items.
- Build common navigation and alignment layouts.
1. Enable Flexbox
.container {
display: flex;
}The element with display: flex becomes a flex container. Its in-flow children become flex items.
2. Main and Cross Axes
.row {
display: flex;
flex-direction: row;
}
.column {
display: flex;
flex-direction: column;
}The main axis follows flex-direction. The cross axis is perpendicular to it. By default, row places items along the inline direction, which is usually horizontal in left-to-right writing mode.
3. justify-content
.container {
display: flex;
justify-content: space-between;
}Justify-content distributes items along the main axis. Common values include flex-start, flex-end, center, space-between, space-around and space-evenly.
4. align-items
.container {
display: flex;
align-items: center;
}Align-items aligns items along the cross axis. Common values include stretch, flex-start, flex-end, center and baseline.
5. Gap
.container {
display: flex;
gap: 16px;
}Gap creates spacing between flex items without adding margins to every child.
6. A Practical Navigation Bar
<nav class="navbar">
<strong>MySite</strong>
<div class="links">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</div>
</nav>.navbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
}
.links {
display: flex;
gap: 16px;
}7. Common Mistake
Justify-content and align-items are relative to the axes, not permanently horizontal and vertical. When flex-direction changes to column, the main axis changes too.