HTML and CSS

Lesson 7 of 10

Lesson ยท 10 min

Flexbox

A new way to lay out items

Normally, block elements stack from top to bottom. Flexbox lets you place items in a row (or a column) and control their space. You turn it on for a container, and its direct children become flex items.

.toolbar {
  display: flex;
}

When you add display: flex, the items sit in a row, next to each other.

Two axes

A flex container has two axes:

  • The main axis runs in the direction of the items. In a row, it is horizontal.
  • The cross axis is at a right angle to it. In a row, it is vertical.

These properties go on the container:

Property What it does
flex-direction row (default) or column. It sets the main axis.
gap Space between the items.
justify-content Places items along the main axis: flex-start, center, flex-end, space-between.
align-items Places items along the cross axis: stretch (default), center, flex-start, flex-end.
flex-wrap wrap lets items move to a new line when there is no room.

Growing items

This property goes on an item, not on the container. flex-grow: 1 lets an item take the free space that is left in the row. If two items have flex-grow: 1, they share the free space equally.

Your turn

The tiles have a blue background. The .row area has a gray background so that you can see how much room the items have.

Tasks

5 to do

  1. Task 1, not checked yet. Turn .row into a flex container. Set display to flex.

  2. Task 2, not checked yet. Put 16px of space between the tiles. Set gap to 16px.

  3. Task 3, not checked yet. Push the first tile to the left edge and the last tile to the right edge. Set justify-content to space-between.

  4. Task 4, not checked yet. Center the tiles from top to bottom. Set align-items to center.

  5. Task 5, not checked yet. Let the first tile grow to fill the free space. Select it with .tile:first-child and set flex-grow to 1.

Task 1 of 5

Turn .row into a flex container. Set display to flex.

All tasks

You can read this file, and you cannot change it. Write your code in style.css.

Preview

Your page shows here