CSS Documentation

CSS Grid Layout

CSS Grid Layout

CSS Grid Layout is a powerful two-dimensional layout system that allows you to create complex web layouts with ease.

Key Concepts

  • Grid Container: The element on which display: grid is applied.
  • Grid Items: The direct children of the grid container.
  • Grid Lines: The dividing lines that make up the structure of the grid.
  • Grid Tracks: The space between two adjacent grid lines (rows or columns).
  • Grid Cell: The intersection of a row and a column in a grid.
  • Grid Area: The total space surrounded by four grid lines.

Creating a Grid Container

To create a grid container, use:

.container {
display: grid;
}

Defining Grid Columns and Rows

Use grid-template-columns and grid-template-rows to define the structure:

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

Grid Gap

To add space between grid items:

.container {
gap: 20px;
}

Placing Items

Use grid-column and grid-row to place items:

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

Best Practices

  • Use fr units for flexible and responsive layouts.
  • Combine Grid with Flexbox for powerful layouts.
  • Use named grid lines for more readable code.
  • Utilize minmax() for responsive grid tracks.
  • Consider using grid-template-areas for complex layouts.

CSS Grid Layout provides a robust system for creating complex web layouts. It offers precise control over the placement and sizing of elements, making it an essential tool for modern web design.