CSS Grid Explained

CSS Grid Explained

The two-dimensional layout system for the web

What is CSS Grid?

CSS Grid Layout is a powerful two-dimensional layout system that lets you create complex web designs with rows and columns. Unlike Flexbox which is one-dimensional, Grid allows precise control over both dimensions simultaneously.

1
2
3
4
5
6

Key Concepts

1. Grid Container

The parent element that becomes a grid when you set display: grid or display: inline-grid.

.container {
  display: grid;
}

2. Grid Items

The direct children of the grid container. These automatically become grid items.

Item 1
Item 2

3. Grid Lines

The dividing lines that make up the structure of the grid. They can be vertical (column lines) or horizontal (row lines).

.item {
  grid-column: 1 / 3; /* Starts at line 1, ends at line 3 */
  grid-row: 1; /* Occupies row line 1 */
}

4. Grid Tracks

The space between two adjacent grid lines (essentially your columns and rows).

.container {
  grid-template-columns: 200px 1fr; /* Two columns */
  grid-template-rows: 100px auto; /* Two rows */
}

5. Grid Areas

Rectangular space surrounded by four grid lines. You can name these areas for easier placement.

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

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

Common Grid Properties

Property Description
grid-template-columns Defines the columns of the grid
grid-template-rows Defines the rows of the grid
grid-template-areas Defines named grid areas
grid-gap / gap Sets the gap between rows and columns
grid-column Positions an item along the column axis
grid-row Positions an item along the row axis
justify-items Aligns items along the row axis
align-items Aligns items along the column axis

Practical Example

/* Create a 3-column layout with flexible sizing */
.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: auto 1fr auto;
  gap: 1rem;
  height: 400px;
}
Header (spans all columns)
Sidebar
Main Content
Right Panel
Footer (spans all columns)

Responsive Grid Example

/* Mobile-first responsive grid */
.container {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

@media (min-width: 768px) {
  .container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 1024px) {
  .container {
    grid-template-columns: repeat(3, 1fr);
  }
}
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6

CSS Grid provides powerful layout capabilities for modern web design.