CSS Flexbox and Grid Cheat Sheet
Flex containers and items, grid tracks, placement and template areas, centering, and common layout patterns.
Updated
Flexbox container#
.row {
display: flex;
flex-direction: row; /* row | column | row-reverse | column-reverse */
justify-content: space-between; /* main axis: flex-start | center | flex-end | space-between | space-around | space-evenly */
align-items: center; /* cross axis: stretch | flex-start | center | flex-end | baseline */
flex-wrap: wrap; /* allow new lines */
gap: 12px; /* space between items */
}justify-contentworks along the main axis (horizontal for rows);align-itemsalong the cross axis.- With
flex-direction: column, the axes swap. align-contentspaces wrapped lines.
Flex items#
Grid container#
.grid {
display: grid;
grid-template-columns: 200px 1fr 2fr; /* fixed + fractions */
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); /* responsive, no media queries */
grid-auto-rows: minmax(100px, auto);
gap: 16px; /* row-gap and column-gap */
place-items: center; /* align + justify items */
}Placing grid items#
.wide { grid-column: span 2; }
.tall { grid-row: span 2; }
.banner { grid-column: 1 / -1; } /* full width: first to last line */
.box { grid-column: 2 / 4; grid-row: 1; }Template areas#
.page {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"nav main"
"footer footer";
min-height: 100dvh;
}
header { grid-area: header; }
nav { grid-area: nav; }
main { grid-area: main; }
footer { grid-area: footer; }
@media (max-width: 700px) {
.page {
grid-template-columns: 1fr;
grid-template-areas: "header" "main" "nav" "footer";
}
}Subgrid lines up nested content with the parent grid: grid-template-rows: subgrid; on an item that spans rows.
Centering#
Common layouts#
/* Sticky footer */
body { min-height: 100dvh; display: flex; flex-direction: column; }
main { flex: 1; }
/* Navbar */
.nav { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
/* Centered content column */
.container { width: min(100% - 2rem, 1100px); margin-inline: auto; }
/* Card grid */
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1.5rem; }
/* Media object */
.media { display: flex; gap: 1rem; align-items: flex-start; }
.media img { flex: none; width: 64px; }Flexbox or Grid?#
Want the full explanations? Go to the Learn CSS course →