Layout with Flexbox and Grid
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: flexon the parent makes its children flex items.justify-contentspreads items along the main axis (a row by default).align-itemsaligns them on the other axis.gapsets the space between items. Use it instead of margins.flex-wrap: wraplets 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.