CSS ยท Chapter 24 of 44

CSS Grid

CSS Grid is a two-dimensional layout system for arranging content into rows and columns simultaneously. Setting display: grid on a container enables grid-template-columns and grid-template-rows to define the structure.

Grid is ideal for whole-page layouts, while flexbox suits one-dimensional component layouts.

Syntax
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;

Defining a grid

grid-template-columns: 1fr 1fr 1fr; creates three equal columns. The fr unit represents a fraction of available space.

Gaps and areas

gap adds space between rows and columns. grid-template-areas lets you name regions and place items visually using grid-area.

Example 1 (css)
.layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  gap: 20px;
}
Output
A two-column layout: fixed 200px sidebar and a flexible main column, with 20px gaps

The fr unit lets the second column fill remaining space after the fixed 200px column.

Key points

  • display: grid enables a two-dimensional grid layout.
  • grid-template-columns/rows define the grid structure.
  • The fr unit distributes remaining space proportionally.
  • gap adds consistent spacing between grid cells.
๐Ÿ’ก Note: Grid and flexbox can be combined: grid for the page layout, flexbox inside components.

๐Ÿ“ Quick Quiz

1. Which property enables CSS Grid on a container?

2. What does the fr unit represent?

3. Which property adds spacing between grid cells?