CSS grid layout
What is CSS Grid?
CSS Grid Layout is a powerful two-dimensional layout system that allows you to create complex layouts with rows and columns simultaneously. Unlike Flexbox (one-dimensional), Grid gives you full control over both axes.
Enabling Grid
css
.container {
display: grid; /* or inline-grid */
}Defining Rows and Columns
css
.container {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
gap: 16px;
}fr— fractional unit, distributes remaining spaceauto— sizes to contentpx,%,rem— fixed sizesminmax(min, max)— flexible range
Key Container Properties
| Property | Description |
|---|---|
grid-template-columns | Defines column sizes |
grid-template-rows | Defines row sizes |
gap / row-gap / column-gap | Spacing between cells |
grid-template-areas | Named grid areas for intuitive layouts |
justify-items | Horizontal alignment of items within cells |
align-items | Vertical alignment of items within cells |
justify-content | Horizontal alignment of the entire grid |
align-content | Vertical alignment of the entire grid |
Key Item Properties
| Property | Description |
|---|---|
grid-column | Which columns the item spans (grid-column: 1 / 3) |
grid-row | Which rows the item spans |
grid-area | Named area or shorthand for row/column placement |
justify-self | Horizontal alignment of a single item |
align-self | Vertical alignment of a single item |
repeat() and minmax()
css
/* 3 equal columns */
grid-template-columns: repeat(3, 1fr);
/* Auto-fill responsive columns */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
/* Auto-fit — collapses empty tracks */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));Named Grid Areas
css
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar content aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }Spanning Multiple Cells
css
.item {
grid-column: 1 / 3; /* Span from column line 1 to 3 */
grid-row: 1 / span 2; /* Start at row 1, span 2 rows */
}auto-fill vs auto-fit
| Value | Behavior |
|---|---|
auto-fill | Creates as many tracks as fit, keeps empty tracks |
auto-fit | Creates tracks, then collapses empty ones so items stretch |
css
/* auto-fit — items stretch to fill space */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));Important:
CSS Grid is ideal for page-level layouts and two-dimensional arrangements. Combine it with Flexbox: use Grid for the overall page structure and Flexbox for component-level alignment inside grid cells.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.