CSS Grid Layout Guide

CSS Grid is a powerful two-dimensional layout system that makes it easy to create complex web layouts. Unlike Flex box, which is primarily for one-dimensional layouts, Grid allows you to work with both rows and columns simultaneously.

Why Use CSS Grid?

  • Two-Dimensional Layout: Control both rows and columns at the same time.
  • Responsive Design: Create flexible layouts that adapt to different screen sizes.
  • Simplified HTML: Reduce the need for wrapper divs and complex nesting.
  • Precise Control: Place items exactly where you want them on the grid.

Basic Grid Setup

To create a grid, you need a container element with display: grid:

index.css
.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: auto;
  gap: 20px;
}

Grid Template Columns

Define how many columns your grid should have:

index.css
/* Three equal columns */
grid-template-columns: 1fr 1fr 1fr;

/* Two columns with different sizes */
grid-template-columns: 2fr 1fr;

/* Fixed and flexible columns */
grid-template-columns: 200px 1fr 100px;

Grid Areas

Use named grid areas for more intuitive layouts:

index.css
.grid-container {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";
}

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

Responsive Grid

Make your grid responsive using media queries:

index.css
.grid-container {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

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

@media (min-width: 1024px) {
  .grid-container {
    grid-template-columns: 1fr 1fr 1fr;
  }
}

Conclusion

CSS Grid is an essential tool for modern web development. It provides the flexibility and control needed to create sophisticated layouts while keeping your HTML clean and semantic. Start experimenting with Grid today to build better, more responsive websites.