CSS grid

CSS Grid is a powerful layout system in CSS designed for creating two-dimensional web layouts. It allows you to define rows and columns and place items within these grid structures with precision. CSS Grid makes it easier to create complex, responsive designs without the need for additional frameworks or extensive CSS workarounds.

Key Features of CSS Grid

Two-Dimensional Layout: It handles both rows and columns simultaneously, unlike Flexbox, which is primarily one-dimensional.

Explicit and Implicit Grids: You can define grid rows and columns explicitly or let the browser generate them implicitly as needed.

Responsive Design: It simplifies responsive design by allowing easy rearrangement of grid items using media queries or the auto-fit and auto-fill properties.

Grid Template Areas: You can define named grid areas to make layout definitions more readable and structured.

Syntax

Define a Grid Container

To use Grid, you need a container element with display: grid or display: inline-grid.


.container {
  display: grid;
  grid-template-columns: 100px 200px auto;
  grid-template-rows: 50px auto 100px;
}

Place Items

You can position child items using properties like grid-column and grid-row.


.item1 {
  grid-column: 1 / 3; /* Span from column 1 to column 3 */
  grid-row: 1 / 2;    /* Span from row 1 to row 2 */
}

Example:


<div class="grid-container">
  <div class="item1">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>
  <div class="item4">4</div>
</div>