2059↗learn.

Layout with Flexbox

Arrange a row that can adapt.

Start with the parent

Set display: flex on a container to arrange its direct children as flex items. The default main axis runs along a row. flex-direction: column changes the main axis to a column.

Distribute space

gap adds space between items. justify-content distributes space on the main axis. align-items aligns items on the cross axis. Their visual directions depend on flex-direction and the writing mode.

Let the layout wrap

flex-wrap: wrap allows items to move onto additional lines when space runs out. Avoid fixed widths that force a narrow screen to scroll sideways.

Try the example

<style>
  body { font-family: sans-serif; padding: 24px; background: #f7f8f2; }
  .shelf { display: flex; gap: 12px; flex-wrap: wrap; }
  .item { flex: 1 1 110px; padding: 24px; background: #d4ef78; border: 1px solid #526d14; }
</style>
<h1>Three useful things.</h1>
<div class="shelf">
  <div class="item">Read</div>
  <div class="item">Make</div>
  <div class="item">Repeat</div>
</div>

Enable JavaScript to edit and run the example in the playground.

Your turn

Add a fourth item, then change flex-direction to column on .shelf.

Check your understanding

Where do you put display: flex?

  • On the container
  • On every child
  • On the stylesheet link
Show answer and explanation

On the container. The container becomes a flex container; its direct children become flex items.

MDN reference ↗

Next lesson →

Search by topic, concept, or language. Escape to close.

Reset local data?