CSS Grid

Design powerful, flexible, and responsive layouts with ease.

What is CSS Grid?

CSS Grid is a two-dimensional layout system that allows you to design web pages using rows and columns together.

  • Create complex layouts easily
  • Work with rows and columns at the same time
  • Perfect for page layouts
  • Cleaner and more readable code

Real-Life Example: Think of CSS Grid like a chessboard or Excel sheet — everything fits neatly into rows and columns.

CSS Grid vs Flexbox

  • Flexbox: One-dimensional (row OR column)
  • Grid: Two-dimensional (rows AND columns)
  • Grid is best for page layout
  • Flexbox is best for components

Tip: Use Grid for the main layout and Flexbox inside grid items.

Creating a Grid Container

To start using CSS Grid, you must define a grid container.

Basic Grid Container


.container {
    display: grid;
}

                

Once display: grid is applied, all child elements automatically become grid items.

Defining Rows and Columns

Use grid-template-columns and grid-template-rows to define the structure of the grid.

3 Column Layout


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

                

Explanation: fr means “fraction of available space”.

Grid Gap (Spacing)

Grid provides easy spacing between rows and columns using gap.

Adding Space Between Items


.container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
}

                

No margins needed — Grid handles spacing cleanly.

Positioning Grid Items

You can control where items appear using column and row lines.

Item Placement


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

                

Meaning: This item spans from column line 1 to 3.

Grid Template Areas

Grid areas allow you to design layouts visually using names.

Page Layout Example


.container {
    display: grid;
    grid-template-areas:
        "header header"
        "sidebar content"
        "footer footer";
    grid-template-columns: 1fr 3fr;
}

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

                

This method is extremely readable and beginner-friendly.

Responsive Grid Layout

CSS Grid makes responsive design simple with auto-fit and minmax().

Responsive Cards Layout


.container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

                

Result: Cards automatically adjust based on screen size.

Best Practices for CSS Grid

  • Use Grid for layout, Flexbox for alignment
  • Prefer fr units over fixed widths
  • Use grid areas for page layouts
  • Combine with media queries when needed

Pro Tip: CSS Grid turns layout problems into simple design decisions.