How do you use CSS Grid?

CSS

The short answer

CSS Grid is a two-dimensional layout system that lets you control both rows and columns at the same time. You define a grid on a container element and place child elements into rows and columns. It is ideal for page layouts, card grids, and any layout that needs alignment in both directions.

Basic grid

.grid {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
gap: 16px;
}

This creates a three-column layout: a 200px sidebar, a flexible main area, and another 200px sidebar. gap adds space between grid items.

Common patterns

Equal columns:

.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 24px;
}

repeat(3, 1fr) creates three equal-width columns. 1fr means one fraction of the available space.

Responsive grid without media queries:

.cards {
display: grid;
grid-template-columns: repeat(
auto-fill,
minmax(250px, 1fr)
);
gap: 24px;
}

This creates as many columns as will fit, each at least 250px wide. As the screen gets narrower, columns wrap to the next row automatically.

Page layout:

.page {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
'header header'
'sidebar main'
'footer footer';
min-height: 100vh;
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}

grid-template-areas gives you a visual map of your layout that is easy to read and change.

Placing items

You can place items at specific positions:

.item {
grid-column: 1 / 3; /* spans columns 1 and 2 */
grid-row: 2 / 4; /* spans rows 2 and 3 */
}

Or use the shorthand:

.item {
grid-area: 2 / 1 / 4 / 3; /* row-start / col-start / row-end / col-end */
}

Alignment

.grid {
/* Align all items */
justify-items: center; /* horizontal */
align-items: center; /* vertical */
/* Align the grid itself within its container */
justify-content: center;
align-content: center;
}
.item {
/* Align a single item */
justify-self: end;
align-self: start;
}

Interview Tip

Show the responsive grid pattern (repeat(auto-fill, minmax(250px, 1fr))) — it is the most impressive one-liner in CSS Grid. Then mention grid-template-areas for page layouts. Knowing both patterns shows you can use Grid for different situations.

Why interviewers ask this

CSS Grid is a core layout tool that every frontend developer should know. Interviewers ask about it to see if you can create layouts without hacks, if you know the responsive patterns, and if you understand the difference between Grid and Flexbox.