Control how things line up

INPUT · Slides

Children that do not fit go onto the next line

01 / 05

To begin with they get "squeezed onto one line"

Children of a display: flex; do not go onto the next line when there is not enough room. They all shrink and force themselves onto one line.

Put six cards in a row and each one gets squashed flat.

02 / 05

wrap allows the break

Write flex-wrap: wrap; on the parent and children that do not fit go onto the next line.

Again it goes on the parent. The children need know nothing.

.cards {  display: flex;  flex-wrap: wrap;}

03 / 05

How many per line depends on the width

You do not write "break after three". It follows from the parent width and the child width.

Parent 480px and child 150px gives three. Narrow the parent and it is two, narrower still and it is one.

Because you never fixed a number, it keeps up when the width changes.

.cards {  width: 480px;}.card {  width: 150px;}

04 / 05

Gaps come from margin

When you do not want the children touching, write margin on them. The same thing opens up the gap to the line below.

Adding gaps means fewer fit on a line, and that is the one thing to watch.

.card {  width: 140px;  margin: 0 8px 8px 0;}

05 / 05

Coping with narrow screens becomes automatic

Allow wrapping and the rows multiply on their own as the screen gets narrower. There are places where you cope without writing an @media at all.

Have a go.