appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Layout with Flexbox and Grid

Lesson 4 of 512 minBeginner

Arrange elements in a row, a column or a grid without hacks.

Two tools cover almost every layout. Flexbox arranges items along one line (a row or a column). Grid arranges them in rows and columns at once.

Flexbox

.bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}
  • display: flex on the parent makes its children flex items.
  • justify-content spreads items along the main axis (a row by default).
  • align-items aligns them on the other axis.
  • gap sets the space between items. Use it instead of margins.
  • flex-wrap: wrap lets items go to the next line when there is no room.

Grid

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
  gap: 1rem;
}

This single rule makes a grid of cards that fills the row, wraps by itself and shrinks to one column on a narrow screen. No media query is needed.

Which one?

Use Flexbox for a toolbar, a menu or the inside of a card. Use Grid for the page layout or any set of items that must line up in both directions. They combine well.

NoteTo center something both ways: display: grid; place-items: center; on the parent.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which property sets the space between flex or grid items?
2. Which tool is best for a toolbar with items in a single row?
3. What does repeat(auto-fit, minmax(14rem, 1fr)) do?