CSS Grid
While Flexbox is one-dimensional (a row or a column), Grid is two-dimensional — it lets you control rows and columns at the same time. It's the best tool for overall page layouts, image galleries, and dashboards.
The Grid Container
.grid {
display: grid;
grid-template-columns: 200px 1fr 1fr; /* 3 columns: fixed, then two flexible */
grid-template-rows: auto 1fr auto;
gap: 16px; /* space between rows and columns */
row-gap: 16px;
column-gap: 24px;
}
/* repeat() avoids writing the same value many times */
.grid-3-equal {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
/* auto-fit / auto-fill — responsive grids with no media queries needed */
.auto-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 20px;
}
fr is Grid's own unit meaning "a fraction of the remaining space" — 1fr 2fr
splits the space into thirds, giving the second column twice as much room as the first.
The Grid Items
.item {
grid-column: 1 / 3; /* start at column line 1, end at line 3 (spans 2 columns) */
grid-row: 1 / 2;
/* Shorthand for span */
grid-column: span 2;
grid-row: span 3;
}
.item {
justify-self: center; /* align this item horizontally within its cell */
align-self: center; /* align this item vertically within its cell */
}
.grid {
justify-items: center; /* same, but set for all items at once, on the container */
align-items: center;
}
Grid Template Areas
Named areas make complex layouts easy to read at a glance:
.layout {
display: grid;
grid-template-columns: 220px 1fr;
grid-template-rows: 70px 1fr 60px;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.footer { grid-area: footer; }
<div class="layout">
<header class="header">Header</header>
<aside class="sidebar">Sidebar</aside>
<main class="content">Main Content</main>
<footer class="footer">Footer</footer>
</div>
Full Examples
Example 1 — a responsive photo gallery:
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 12px;
}
.gallery img {
width: 100%;
height: 180px;
object-fit: cover;
border-radius: 8px;
}
Example 2 — a pricing card row with one card highlighted and slightly larger:
.pricing {
display: grid;
grid-template-columns: 1fr 1.2fr 1fr;
align-items: center;
gap: 20px;
}
.pricing .featured {
transform: scale(1.05);
border: 2px solid #F5A623;
}