Understanding CSS Grid Layout

CSS Grid Layout is a powerful two-dimensional layout system for the web. It lets you lay out content in rows and columns. It's designed to solve the common problem of laying out a web page without having to use hacks, floating elements, or positioning elements.

Key Concepts

Grid Container and Grid Items

The grid is created by defining a grid container (an element with display: grid; or display: inline-grid;) and its children elements become grid items.

Grid Lines, Tracks, and Cells

Defining Grid Structure

You can define the structure of your grid using properties like:

Example: Basic Grid Structure

Item 1
Item 2
Item 3
Item 4
Item 5

.grid-container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr; /* Three columns with different widths */
  grid-template-rows: auto 100px;    /* Two rows: auto height and fixed 100px */
  gap: 15px;
}

            

Placing Grid Items

Items can be placed automatically into the grid, or you can explicitly define their position using properties like:

Example: Placing Items

Spans 2 Columns
Item 2
Spans 2 Rows

.item-spanning-columns {
  grid-column: 1 / 3; /* Starts at line 1, ends at line 3 (spans 2 columns) */
  grid-row: 1;
}

.item-spanning-rows {
  grid-column: 3;
  grid-row: 1 / 3; /* Starts at line 1, ends at line 3 (spans 2 rows) */
}

            

Useful Units and Functions

Advantages of CSS Grid

CSS Grid is a fundamental tool for modern web layout. Mastering it will significantly improve your ability to build sophisticated and responsive user interfaces.