Flexbox arranges a group of child elements along one main axis. It works well for navigation bars, button groups, card rows, and interfaces that need reliable alignment or distribution of remaining space.
Create a flex container
Start with display: flex on the shared parent. The parent becomes the flex container, and its direct children become flex items. The main axis is horizontal by default, so items appear from left to right.
<nav class="nav">
<strong>Leaflet</strong>
<a href="#courses">Courses</a>
<a href="#practice">Practice</a>
<button>Sign in</button>
</nav>.nav {
display: flex;
align-items: center;
gap: 14px;
}justify-content controls distribution on the main axis. align-items controls alignment on the cross axis, and gap creates consistent space between neighboring items. Changing flex-direction to column makes the main axis vertical.
Handle limited space
Flex items try to stay on one line by default. Add flex-wrap: wrap so items can move onto another line in a narrow viewport. An item with margin-right: auto can also consume the remaining main-axis space and push later items to the other side.
Live style lab: Flexbox
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
A useful order of work
- Find the shared parent and set
display: flex. - Choose the main-axis direction and alignment on both axes.
- Use
gapfor item spacing and test whether narrow screens need wrapping. - Avoid fixed widths used only to force spacing, because longer text can break them.
KNOWLEDGE QUIZ
Practice: build a wrapping course navigation
Write Flexbox styles for the supplied navigation.
- Make the navigation a flex container and vertically center its items.
- Use gap for consistent spacing and allow wrapping on narrow screens.
- Give the button a dark background with clearly readable light text.
HTML structure
<nav class="nav">
<strong>Leaflet</strong>
<a href="#courses">Courses</a>
<a href="#practice">Practice</a>
<button>Sign in</button>
</nav>