Flexbox
Start a Flexbox layout
Turn a parent into a flex container and identify the main axis, cross axis, container properties, and item properties.
Flexbox is the layout tool I reach for most often. It lays out a group of elements in one direction, a row or a column, and gives you simple controls for spacing and alignment.
You turn it on with one declaration on the parent. Here is a navigation bar where the links sit side by side with some space between them:
.navigation {
display: flex;
gap: 1rem;
}
The .navigation element becomes the flex container. Its direct children become flex items. Only the direct children. A link nested inside a <li> inside the container is not a flex item, the <li> is.
The two axes
Every flex container has a main axis and a cross axis. By default the main axis is the row direction, so in English it runs left to right. The cross axis is perpendicular to it, top to bottom.
Set flex-direction: column and the two swap. Now the main axis runs top to bottom.
Don’t think of “row” as a synonym for “horizontal” forever. In a vertical writing mode, a row runs vertically. Flexbox follows the writing direction, which is why we call the axes main and cross instead of horizontal and vertical.
Container properties and item properties
Some properties go on the container and organize the whole group: flex-direction, justify-content, align-items, flex-wrap, and gap.
Others go on a single item and change only that child: flex, align-self, and order.
If a property does nothing, check which element you put it on. justify-content on an item is silently ignored.
What you get by default
Without any other rule, flex items:
- stay on one line and don’t wrap
- can shrink when there isn’t enough room
- stretch to fill the cross axis when they have no explicit height
There is one catch with shrinking. An item won’t shrink below the width of its longest unbreakable word. A long URL inside a flex item can push the whole row wider than the page. We’ll handle that when we look at sizing.
Flexbox never changes the HTML. It rearranges boxes visually, but screen readers and the Tab key follow the source order. So keep the source order the one that makes sense when read out loud.
Open your course page, add display: flex to the header, and turn on the Flexbox overlay in DevTools. Switch flex-direction between row and column. Before you touch any alignment property, say out loud which axis is main and which is cross. That habit saves you from guessing between justify-content and align-items every time.
Lesson completed