Flexbox: arranging things in a line
One line of CSS puts things in a row. Then: spacing them out, lining them up, letting them wrap, and deciding which one takes the extra space.
By the end you can
- Put things in a row or a column and space them evenly
- Line things up across the line, including centring
- Let a row wrap onto the next line instead of overflowing
- Decide which item takes up the leftover space
Easier if you did first
step 1 of 4
Making a row
By default, block elements stack. Each one takes its own line, like paragraphs in a book.
display: flex changes that for the children of one box: they line up side by side instead.
The important part, and the part people get wrong: you set display: flex on the container, never on the things you want in a row. You are telling the parent how to arrange its children.
gap sets the space between them. Before gap existed, people put a margin on every child and then fought to remove it from the last one. gap does the right thing by itself.
flex-direction decides which way the line runs: row is the default, column stacks them again but with all the flex tools available.
Turn the cards on the right into a row with space between them.
.plans {
display: flex; the children now sit in a line
gap: 16px; space between them, not around them
}
flex-direction: row; side by side, the default
flex-direction: column; stacked, with flex still in chargeWhat these words mean
- display: flex
- Arrange this element's children in a line.
- flex container
- The element you put display: flex on.
- flex item
- Each direct child of that container.
- gap
- Space between items. Never added to the outside edges.
- flex-direction
- Which way the line runs: row or column.
Easy to get wrong
display: flex on the cards
display: flex on the box holding them
Flex arranges an element's children, so putting it on a card arranges the things inside that card instead. The cards themselves stay stacked and nothing looks any different.
margin-right on every card to space them
gap on the container
The last card ends up with a margin nobody wants, so you write another rule to remove it. gap puts space only between items.
What we check
- .plans is a flex container
- There is a gap between the cards
- All three cards sit on the same line