Control how things line up

INPUT · Slides

The parent decides the arrangement

01 / 05

Where you write it changes

float went on the children you wanted in the row. Flexbox is the other way round: it goes on the parent that holds them.

That turn of thinking is the important bit. The children need nothing at all.

<div class="menu">  <div class="item">Morning</div>  <div class="item">Midday</div></div>

02 / 05

One line

Write display: flex; on the parent. That alone puts the children in a row from the left.

No clear box, and no working out widths; as many fit as fit.

.menu {  display: flex;}

03 / 05

The children can stay as they are

Not only do you not write float on the children,

  • the heights match automatically
  • you do not add an empty box
  • with no width written they come out the size of their contents

The parent does the arranging, so the children only have to think about what is inside them.

04 / 05

The parent decides the position too

Write justify-content on the parent and you decide where along the row they sit. These three come up most.

  • flex-start … to the left (what you get to begin with)
  • center … in the middle
  • space-between … out to both ends with the gaps shared evenly
.menu {  display: flex;  justify-content: center;}

05 / 05

Both ends becomes instant

Logo on the left, menu on the right — that shape you were writing with float: left; and float: right; is one line of space-between.

Have a go.

.header {  display: flex;  justify-content: space-between;}