Build galleries and complete page layouts with CSS Grid's columns, rows, and named areas.
Open this lesson in KodokonFlexbox aligns along one axis; Grid controls both at once. As soon as your mockup looks like a table - photo gallery, dashboard, full page with header, sidebar, and footer - Grid is the right tool. The container defines the structure in columns and rows, and the children place themselves automatically or exactly where you choose.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}The fr (fraction) unit shares out the available space: 1fr 2fr creates two columns where the second is twice as wide. Unlike percentages, fr accounts for the gap without any calculation on your part. To highlight an element, make it span several tracks with grid-column and grid-row.
.featured {
grid-column: span 2;
grid-row: span 2;
}For a full page, grid-template-areas lets you draw the mockup directly in the CSS. Each string represents one row of the grid, each word a named area. A child then places itself with grid-area. The result reads like an architect's blueprint: it's the most readable method for a page layout.
.page {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
}
.site-header { grid-area: header; }
.site-nav { grid-area: sidebar; }
.site-main { grid-area: main; }
.site-footer { grid-area: footer; }fr unit represent in grid-template-columns: 1fr 2fr?grid-template-columns: 3grid-template-columns: repeat(3, 1fr)grid-columns: 1fr 3grid-template-areas used for?grid-area