CSS Grid Layout: A Modern Approach to Web Layouts

CSS Grid Layout is a powerful two-dimensional layout system for the web. It lets you lay out content in rows and columns, offering unprecedented control over the structure of your web pages. Unlike Flexbox, which is primarily for one-dimensional layouts, Grid excels at complex, multi-directional arrangements.

What is CSS Grid?

CSS Grid Layout enables you to create sophisticated layouts with ease. It divides a page into major sections or smaller components, and defines the relationship between elements on the page. It's designed to solve layout problems that were previously difficult or impossible to achieve with traditional CSS methods like floats or even Flexbox alone.

Core Concepts

Understanding Grid involves a few key terms:

Creating a Grid

To create a grid, you simply apply display: grid; to a container element:

.grid-container {
    display: grid;
}

By default, this creates a single column grid. To define the structure, you'll use specific Grid properties.

Key Grid Container Properties

Key Grid Item Properties

The fr Unit

The fr unit is a flexible unit representing a fraction of the available space in the grid container. It's incredibly useful for creating responsive layouts. For example, grid-template-columns: 1fr 2fr 1fr; creates three columns where the second column takes up twice as much space as the first and third.

Practical Example

Let's create a simple responsive grid layout:

Item 1
Item 2 (Spans 2 columns)
Item 3 (Spans 2 rows)
Item 4
Item 5

.grid-demo {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
    grid-template-rows: auto auto; /* 2 rows, height determined by content */
    gap: 10px; /* Space between items */
}

.grid-item {
    /* Styling for individual items */
}

.grid-item-span-2 {
    grid-column: span 2; /* Makes this item span 2 columns */
}

.grid-item-row-span-2 {
    grid-row: span 2; /* Makes this item span 2 rows */
}
            

Try It Yourself!

Enter a number to define the columns in the demo grid: