⊞CSS Grid Complete Guide

CSS Grid Basics

CSS Grid is a two-dimensional layout system that lets you control rows and columns simultaneously. You create a grid by applying display: grid to a container, then define its structure.

display: gridgrid-template-columnsgrid-template-rowsgrid

1. Enabling Grid

Add display: grid to any container to make it a grid container. Its direct children automatically become grid items. Without any other properties, items stack in a single column (same as block layout).

Live Demo
Item 1
Item 2
Item 3
CSS
.container {
  display: grid;
}
/* children stack in one column by default */
πŸ’‘ Unlike flexbox (1D), grid is 2D β€” you can control both axes at once.

2. grid-template-columns

Define how many columns and how wide each column should be. Each space-separated value creates one column track.

Live Demo
200px
100px
150px
CSS
.container {
  display: grid;
  grid-template-columns: 200px 100px 150px;
}

3. grid-template-rows

Define row track sizes explicitly. If you have more items than rows, additional rows are created implicitly with auto height.

Live Demo
Row 1 (80px)
Row 1 (80px)
Row 2 (40px)
Row 2 (40px)
Row 3 (60px)
Row 3 (60px)
CSS
.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 80px 40px 60px;
}

4. grid Shorthand

The grid shorthand sets both rows and columns together using a slash separator: "rows / columns".

Live Demo
1
2
3
4
5
6
CSS
.container {
  display: grid;
  /* rows / columns */
  grid: 60px 80px / 1fr 1fr 1fr;
}
/* equivalent to: */
.container {
  grid-template-rows: 60px 80px;
  grid-template-columns: 1fr 1fr 1fr;
}
πŸ’‘ The grid shorthand is powerful but complex. It also resets grid-auto-flow, grid-auto-rows, and grid-auto-columns.

5. The auto Keyword

Use auto to let a track size itself based on its content. Auto columns/rows expand to fit their largest item.

Live Demo
Short
A medium length item
Long content here!
CSS
.container {
  display: grid;
  grid-template-columns: auto auto auto;
}
/* each column is as wide as its content */

6. Mixing Units

You can freely mix px, %, em, fr, auto and other units in the same track definition.

Live Demo
100px
1fr
20%
CSS
.container {
  display: grid;
  grid-template-columns: 100px 1fr 20%;
  /* fixed | flexible | percentage */
}