Basic

Placing things side by side

Getting elements onto one row used to need tricks. Now there are two real tools: flexbox for a row of items, and grid for a two dimensional layout. Choosing one of those two covers almost every layout you will be asked for.

What you will see

The row sits in the middle of the container. justify-content works along the row, which is the axis flexbox has.

About 1 min of reading

Try It

Put three items on one row.

1

The container

.toolbar { display: flex; gap: 12px; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The three children sit on one line with 12 pixels between them, without any widths set.
2

Centre them

.toolbar { display: flex; justify-content: center; gap: 12px; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The row sits in the middle of the container. justify-content works along the row, which is the axis flexbox has.

Data Flow

A container arranges its children.
1 Choose the container type
↓
2 Name the tracks or the direction
↓
3 Let children size themselves
↓
4 Check with real content
Why this works
Flex the row, grid the page

A toolbar, a list of cards, and a row of icons are flex. A page with a sidebar and a header, or a calendar, is grid. The choice is which direction the layout varies in, and that question is quick.

Let content set the size

A layout that works when a label is twice as long as you expected is a layout that does not depend on fixed widths. Fixed sizes look finished and break on the first real text, which is the fastest way to fail a review.

Examples

Flexbox for a row

display: flex on the parent puts the children on one line. justify-content spreads them and align-items lines them up. That is the whole tool for a row, and it works without knowing how many children there are.

Grid for rows and columns

display: grid with a template names the tracks explicitly. When the layout is genuinely two dimensional, grid states both directions and flexbox states one, which is the reason to pick it.

Default is a block

A div already fills its own line. That default is why things stack without any CSS, and why a layout problem is often 'these should not stack' rather than 'these should'.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← The box model
Previous Lesson
The box model
Next Lesson
One page, many widths
One page, many widths →