CSSadvanced 9 min
Cards, sidebars and the holy-grail page layout using flexbox and grid together.
How to combine grid and flexbox to build three patterns you will use constantly: a responsive card grid, a sidebar layout and a full page with header, sidebar, content and footer.
Most real pages are variations of a few layouts. Learning these patterns means you can build almost any page without searching for a recipe each time.
Pattern 1: auto-fit card grid. A grid that fits as many columns as the width allows, with no media query:
minmax(140px, 1fr) means "at least 140px, at most an equal share". auto-fit adds columns until no more fit.
Pattern 2: sidebar plus content.
Pattern 3: the holy grail. Header on top, footer at the bottom, a sidebar and main content between them. Grid areas let you draw the layout in words:
Use flexbox inside the pieces (to centre text in a card or space out a header's links) and grid for the outer layout.
grid-template-areas draws the page: the header and footer span both columns, and the sidebar and main sit side by side.grid-area. The order in the HTML does not matter for placement.grid-template-columns: 100px 1fr gives a fixed sidebar and a flexible main area.auto-fit plus minmax makes a card grid that adds or removes columns as the width changes.Move the sidebar to the right by changing the areas to "main side" and the columns to 1fr 100px.
auto-fit and minmax would do.auto-fit and minmax make responsive card grids without media queries.grid-template-areas draws a page layout in words.You finished the CSS track. Try the practice exercises to lock it in.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 12px;
}.layout { display: grid; grid-template-columns: 160px 1fr; gap: 12px; }.page {
display: grid;
grid-template-areas:
"header header"
"side main"
"footer footer";
grid-template-columns: 120px 1fr;
}
header { grid-area: header; }<style>
* { box-sizing: border-box; }
.page {
display: grid;
grid-template-areas:
"header header"
"side main"
"footer footer";
grid-template-columns: 100px 1fr;
gap: 8px;
font-family: system-ui, sans-serif;
font-size: 14px;
}
.page > * { padding: 10px; border-radius: 6px; }
header { grid-area: header; background: #c7d2fe; display: flex; justify-content: space-between; }
aside { grid-area: side; background: #fde68a; }
main { grid-area: main; background: #d1fae5; }
footer { grid-area: footer; background: #fecaca; text-align: center; }
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
gap: 6px;
margin-top: 8px;
}
.cards div { background: white; padding: 8px; text-align: center; border-radius: 6px; }
</style>
<div class="page">
<header><strong>Logo</strong><span>Menu</span></header>
<aside>Sidebar</aside>
<main>
Content
<div class="cards"><div>A</div><div>B</div><div>C</div><div>D</div></div>
</main>
<footer>Footer</footer>
</div>