Sub topic 1
Creating a flex container with display: flex
Prerequisites
This chapter assumes you know basic HTML structure and elements, CSS selectors and the cascade, the box model (content, padding, border, margin), and length units such as px, rem and percentages.
The working model
Flexbox arranges items along a single line, called an axis. You turn it on with one declaration on a parent element:
.nav {
display: flex;
}The element with display: flex becomes a flex container. Its direct children become flex items. Grandchildren are not affected. They stay in normal flow inside their own parent, unless that parent is also made a flex container.
A flex container is a block-level box, so it fills the available width like a div. If you want it to sit inline with surrounding content, use display: inline-flex instead. Inside, the layout rules are the same.
What changes for the children
Once the parent is a flex container, its children behave differently from normal block or inline content:
- Items are laid out in a row by default, left to right in a left-to-right language.
- Items are blockified. A
spanchild behaves like a block-level box, sowidthandheightapply to it. - Items shrink to fit their content instead of stretching to full width.
- Items stretch to the height of the tallest item in the row.
- Margins between items do not collapse.
float,clearandvertical-alignhave no effect on items.
A worked example
Here is the markup and the CSS.
<div class="nav">
<a href="/">Home</a>
<a href="/docs">Docs</a>
<a href="/blog">Blog</a>
</div>.nav {
display: flex;
gap: 1rem;
}Without display: flex, the three links are inline and flow like text. With it, each link is a flex item, and they sit in a row separated by 1rem. Adding gap is covered in a later chapter. Here it only keeps the links from touching.
Text nodes that sit directly inside the container are wrapped in an anonymous flex item. Whitespace-only text is ignored, so the line breaks in the HTML above do not create extra items.
Common errors
- Styling the wrong element.
display: flexgoes on the parent, not on the items you want to arrange. - Expecting nested elements to be flex items. Only direct children participate. To lay out a link inside a list item, make the
lia flex container as well. - Using
display: flexwhereinline-flexis needed. A block-level container takes a full line, which can look like extra space beside it.
Check your understanding
Exercise
A ul has display: flex. Each li contains an a element. You apply flex-grow to the a elements, but nothing changes. Why, and what is the fix?
Show answer
Only direct children of the flex container are flex items, and the a elements are grandchildren. flex-grow has no effect on them. Apply it to the li elements instead, or make each li a flex container with display: flex so its a becomes a flex item.