CSS

CSS Grid Layout Guide

Learn CSS grid for two-dimensional layouts. Create complex responsive designs with grid-template and grid-area.

Grid Basics

CSS Grid is a two-dimensional layout system that controls rows and columns:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: auto;
  gap: 16px;
}

Defining the Grid

grid-template-columns

Define column sizes and count

grid-template-columns: 200px 1fr 1fr; /* 固定 + 弹性 */
grid-template-columns: repeat(3, 1fr); /* 3 等分 */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-template-rows

Define row sizes

grid-template-rows: 100px auto 100px;

Gap and Alignment

gapRow and column gap
row-gapRow gap only
column-gapColumn gap only
justify-itemsHorizontal align items
align-itemsVertical align items
place-itemsShorthand

Grid Areas

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

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

Common Layout Examples

Responsive Grid

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

Holy Grail Layout

.container {
  display: grid;
  grid-template-areas:
    "header header header"
    "nav main aside"
    "footer footer footer";
  grid-template-columns: 200px 1fr 200px;
}

Related Tool

Grid Generator

Visual Grid layout