CSS Intermediate: Layout and Responsive Design
Flexbox: One-Dimensional Layout
In this lesson you will
- Turn an element into a flex container
- Control direction, spacing and alignment
- Let items grow, shrink and wrap
Introduction
For years, putting things side by side or centring something took awkward tricks. Flexbox solved this. It is a layout system for arranging items along one line, either a row or a column. Navigation bars, button groups and card rows are all natural fits.
The simple explanation
Flexbox lets a parent element control how its children are laid out.
You make the parent a flex container with display: flex. Its direct children become flex items.
Without display: flex those three blocks would stack vertically. Now they sit in a row, and gap adds space between them.
Quick quiz
Where do you put display: flex?
Direction
flex-direction chooses the main axis: row (default, left to right) or column (top to bottom).
Spacing and alignment
Two properties do most of the work:
justify-contentaligns items along the main axis (for a row: left to right).align-itemsaligns them along the cross axis (for a row: top to bottom).
Common justify-content values: flex-start, center, flex-end, space-between, space-around. To centre something perfectly, use justify-content: center and align-items: center together.
Quick quiz
In a row flex container, which property centres items vertically?
Growing, shrinking and wrapping
flex: 1on an item lets it grow to take the free space. Two items withflex: 1share it equally.flex-wrap: wraplets items move to a new line when they run out of room.
flex: 1 1 120px means: grow, shrink, and start from a base size of 120px. The items wrap on narrow screens without any media query.
Try it yourself
Build a simple navigation bar: a flex container with the logo on the left and three links on the right. Hint: put the links in their own div and use justify-content: space-between.
Summary
display: flexon the parent arranges its children along a line.flex-directionsets row or column.gapspaces items.justify-contentis the main axis,align-itemsthe cross axis.flex: 1grows items, andflex-wrap: wraplets them wrap.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading