Skip to main content
Practice Problems

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 space
  • auto — sizes to content
  • px, %, rem — fixed sizes
  • minmax(min, max) — flexible range

Key Container Properties

PropertyDescription
grid-template-columnsDefines column sizes
grid-template-rowsDefines row sizes
gap / row-gap / column-gapSpacing between cells
grid-template-areasNamed grid areas for intuitive layouts
justify-itemsHorizontal alignment of items within cells
align-itemsVertical alignment of items within cells
justify-contentHorizontal alignment of the entire grid
align-contentVertical alignment of the entire grid

Key Item Properties

PropertyDescription
grid-columnWhich columns the item spans (grid-column: 1 / 3)
grid-rowWhich rows the item spans
grid-areaNamed area or shorthand for row/column placement
justify-selfHorizontal alignment of a single item
align-selfVertical 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

ValueBehavior
auto-fillCreates as many tracks as fit, keeps empty tracks
auto-fitCreates 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems