CSS Grid Basics
Building two-dimensional layouts with grid-template-columns, rows, and named areas.
អាន 2 នាទី
Where Flexbox excels at one-dimensional layout (a row or a column), CSS Grid is built for two dimensions at once — rows and columns together. Reach for Grid when you're laying out a whole page or a card grid, not just a single line of items.
Defining a grid
.gallery {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 16px;
}<div class="gallery">
<img src="/1.jpg" alt="" />
<img src="/2.jpg" alt="" />
<img src="/3.jpg" alt="" />
<img src="/4.jpg" alt="" />
</div>display: grid turns a container into a grid, and grid-template-columns defines the columns. fr is a "fraction" unit unique to Grid — 1fr 1fr 1fr means three equal-width columns that share the available space. Children flow into the grid automatically, wrapping to a new row once a row's columns are filled, with no flex-wrap equivalent needed.
Responsive columns without a media query
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}This single line is one of Grid's most useful patterns: repeat(auto-fit, minmax(200px, 1fr)) says "fit as many columns as you can, each at least 200px wide, and stretch them to share any leftover space." The number of columns adjusts automatically as the container resizes — a card grid that reflows from four columns to two to one, with no @media breakpoints at all.
Rows
.dashboard {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: 64px 1fr;
}grid-template-rows works the same way as columns but for the vertical axis. Combined here, this defines a classic app shell: a fixed-width sidebar column and a fluid content column, with a fixed-height header row above a fluid content row.
Named grid areas
.dashboard {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-areas:
"sidebar header"
"sidebar main";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }<div class="dashboard">
<header class="header">...</header>
<aside class="sidebar">...</aside>
<main class="main">...</main>
</div>grid-template-areas lets you literally draw the layout as ASCII art, naming each region and then assigning grid-area on the children that belong there. This reads far more clearly than tracking numeric row/column line positions, especially once a layout has more than two or three regions — and rearranging the layout for a different screen size is often just rewriting the area strings inside a media query, without touching the HTML at all.