CSS Tutorial

Grid

Grid is a powerful layout system in CSS that provides flexibility and control over how elements are arranged on a web page. It allows you to create complex grid-based layouts with ease.

Key Concepts:

  • Grid Container: The parent element that contains the grid layout.
  • Grid Items: The individual elements that occupy positions within the grid.
  • Grid Columns: Vertical divisions of the grid.
  • Grid Rows: Horizontal divisions of the grid.
  • Grid Gaps: The spacing between grid tracks (columns and rows).
  • Grid Areas: Named regions within the grid that can span multiple columns and rows.

Steps to Use Grid:

  • Define the Grid Container: Use the display: grid property on the parent element.
  • Set Grid Tracks: Specify the number and size of grid columns and rows using the grid-template-columns and grid-template-rows properties.
  • Place Grid Items: Use the grid-column and grid-row properties to position items within the grid.
  • Control Gaps: Use the grid-gap or grid-column-gap and grid-row-gap properties to specify the spacing between tracks.
  • Create Grid Areas: Use the grid-template-areas property to define named regions. Use the grid-area property on grid items to place them in these areas.

CSS Example:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 1em;
}

.grid-item {
  grid-column: span 2;
  grid-row: 2;
  background: blue;
}

This example creates a 3-column, 2-row grid with a 1em gap between tracks. The grid item spans 2 columns and is positioned in the second row, resulting in the following layout:

______________________________
|     |     |     |
|-----+-----+-----|
|     |     |     |
|-----+-----+-----|
|           |
|           |
|           |
|____________________________|