CSS Grid Introduction

Subject: css

CSS Grid Introduction

CSS Grid Layout is a powerful two-dimensional layout system that allows you to design web pages using both rows and columns. Unlike Flexbox, which is one-dimensional (row or column), CSS Grid works across both axes, making it ideal for complex and responsive designs.


Why Use CSS Grid?

  • Create complex layouts with rows and columns
  • Design responsive websites with fewer media queries
  • Align items both horizontally and vertically
  • Eliminate float-based or table-based layout structures
  • Combine easily with Flexbox for complete layout control

CSS Grid Key Features

  • Define tracks using grid-template-rows and grid-template-columns
  • Place items with grid-row, grid-column, or grid-area
  • Supports both explicit and implicit grid layouts
  • Align content using justify-items, align-items, and place-items

Basic Example: 2×2 Grid Layout


Explanation

  • The container uses display: grid to enable grid layout
  • grid-template-columns: 1fr 1fr creates two equal-width columns
  • grid-template-rows: auto auto lets rows adjust height automatically
  • gap: 20px adds spacing between grid items

One-Dimensional vs Two-Dimensional

  • Flexbox: best for layouts in a single direction (row OR column)
  • Grid: ideal when you need control over both rows AND columns

Best Practices

  • Use Grid when you need row + column layout control
  • Use Flexbox for simpler one-directional flows
  • Combine both (Grid for overall layout, Flexbox for content inside grid items)
  • Use units like fr, %, or auto for flexible track sizing

Common Use Cases

  • Full-page layouts (e.g., header, sidebar, content, footer)
  • Image or video galleries
  • Dashboards with widgets
  • Card-based UI components
  • Complex forms and structured templates

Key Takeaways

  • CSS Grid is a true 2D layout system
  • Use display: grid to initiate grid behavior
  • Use grid-template-rows and grid-template-columns to define structure
  • Use gap to add space between items
  • Great for both entire layouts and modular components