Logo
Technical Article

CSS Grid Layout Guide

2 min read

CSS Grid Layout is a two-dimensional layout system designed for the web. It lets you lay out items in rows and columns simultaneously.

Basic Concepts#

Grid Container#

To create a grid container, set display: grid on an element:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;
}

Grid Tracks#

Grid tracks are the spaces between grid lines. You define them using:

  • grid-template-columns
  • grid-template-rows

The fr Unit#

The fr unit represents a fraction of the available space:

/* Three equal columns */
grid-template-columns: 1fr 1fr 1fr;

/* First column twice as wide */
grid-template-columns: 2fr 1fr 1fr;

Placing Items#

You can explicitly place items using line numbers:

.item {
  grid-column: 1 / 3; /* Spans columns 1-2 */
  grid-row: 1 / 2;
}

Named Grid Areas#

Create named areas for more semantic layouts:

.container {
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }

Responsive Grids#

Use auto-fit and minmax() for responsive layouts:

grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));

CSS Grid is now supported in all modern browsers and is the go-to solution for complex layouts.

Resources#