Skip to main content
HTML & CSS Foundations·Lesson 4 of 5

CSS Grid

CSS Grid is a two-dimensional layout system that handles both rows and columns simultaneously. While Flexbox is great for one-direction flow, Grid shines when you need precise control over a full page or component layout.

Basic Grid

Apply display: grid and define columns:

Ctrl+Enter
HTML
CSS
JS
Preview

This creates a 3-column grid. Items flow left-to-right, wrapping to new rows automatically. The fr unit distributes available space proportionally — three 1fr columns each get one-third.

Defining Rows and Columns

Ctrl+Enter
HTML
CSS
JS
Preview

You can mix units freely:

UnitBehavior
1frTakes a fraction of remaining space
200pxFixed pixel width
autoSizes to content
minmax(200px, 1fr)At least 200px, grows up to 1fr

The repeat() function

Instead of writing 1fr 1fr 1fr 1fr, use repeat():

Ctrl+Enter
HTML
CSS
JS
Preview

Grid Template Areas

Named areas let you define layouts visually in CSS:

Ctrl+Enter
HTML
CSS
JS
Preview

The grid-template-areas property maps directly to how the layout looks. Each string is a row, and each word is a column. Use . for empty cells:

grid-template-areas:
  "header header"
  ".      main"
  "footer footer";

Placing Items

Place items on specific grid lines using grid-column and grid-row:

Ctrl+Enter
HTML
CSS
JS
Preview

Line numbers start at 1. Negative numbers count from the end, so -1 is the last line.

Auto-Flow and Implicit Grids

When items overflow the explicit grid, CSS creates implicit rows or columns:

Ctrl+Enter
HTML
CSS
JS
Preview

Change the flow direction with grid-auto-flow:

Ctrl+Enter
HTML
CSS
JS
Preview

Responsive Grids Without Media Queries

The most powerful Grid technique is auto-fitting columns that adapt to available space:

Ctrl+Enter
HTML
CSS
JS
Preview

This creates as many 250px-minimum columns as fit. As the viewport shrinks, columns drop to new rows. No media queries needed.

  • auto-fill — creates as many tracks as fit, even if empty.
  • auto-fit — same, but collapses empty tracks so items can stretch wider.
Ctrl+Enter
HTML
CSS
JS
Preview

Alignment in Grid

Grid supports the same alignment properties as Flexbox, plus a few extras:

Ctrl+Enter
HTML
CSS
JS
Preview

Common Grid Patterns

Dashboard layout

Ctrl+Enter
HTML
CSS
JS
Preview
Ctrl+Enter
HTML
CSS
JS
Preview

Holy grail layout

Ctrl+Enter
HTML
CSS
JS
Preview