CSS Grid

CSS Grid Layout is a revolutionary two-dimensional layout system for the web. Unlike Flexbox, which is primarily designed for one-dimensional layouts (either a row or a column), CSS Grid allows you to work with both rows and columns simultaneously. This gives you the power to create complex, magazine-style layouts and intricate web application interfaces without relying on messy floats or hacky positioning.

Developer Tip: Think of CSS Grid as the "skeleton" of your page layout, while Flexbox is perfect for aligning smaller components (like buttons or navigation links) inside those grid areas.

Basic Concepts

To master Grid, you need to understand the relationship between the parent and its children:

Grid Container: This is the parent element where you apply display: grid;. It creates the environment where the grid lives and defines how many columns and rows will exist.

Grid Items: These are the direct children of the container. Once the parent becomes a grid, these items automatically fall into "grid cells" unless you manually tell them to span multiple rows or columns.

Common Mistake: Only direct children of the grid container become grid items. If you have a nested <div> further down the tree, it won't obey the grid rules unless you also make its parent a grid container.

Creating a Grid Container

The first step in any grid layout is defining your columns. The fr unit (fractional unit) is a game-changer here—it represents a fraction of the available space in the grid container.

.grid-container {
    display: grid;
    /* This creates three columns that share the space equally */
    grid-template-columns: 1fr 1fr 1fr; 
    /* Modern property for spacing between cells */
    gap: 20px; 
}
Best Practice: Use the gap property instead of the older grid-gap. While grid-gap still works in most browsers, gap is the standardized shorthand now used for both Grid and Flexbox.

Grid Lines and Tracks

  • Grid Lines: These are the invisible horizontal and vertical lines that divide the grid. Crucially, these lines are numbered. In a 3-column grid, there are 4 vertical lines.
  • Grid Tracks: This is simply the space between any two adjacent lines. In plain English, a track is a "row" or a "column."

Example

In this example, we mix absolute units (pixels) with flexible units (fr) to create a fixed sidebar with a flexible content area.

.grid-container {
    display: grid;
    /* Column 1: 100px fixed, Column 2: 1 part, Column 3: 2 parts of remaining space */
    grid-template-columns: 100px 1fr 2fr; 
    /* Row 1 fits the content, Row 2 is exactly 200px tall */
    grid-template-rows: auto 200px; 
    gap: 15px;
}
Watch Out: Grid line numbering starts at 1, not 0. If you have 3 columns, the lines are numbered 1, 2, 3, and 4. You can also use negative numbers to count backward from the end (e.g., -1 is the very last line).

Placement of Grid Items

Using Line Numbers

You can tell an item exactly where to sit by referencing the start and end lines. This allows you to create layouts where items overlap or leave specific gaps.

.grid-item {
    /* Starts at vertical line 2 and spans across 2 columns */
    grid-column: 2 / span 2; 
    /* Occupies the first row only */
    grid-row: 1; 
}

Using Named Areas

Named areas are the most intuitive way to use CSS Grid. It allows you to "draw" your layout directly in your CSS using strings.

.grid-container {
    display: grid;
    grid-template-columns: 200px 1fr 1fr;
    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; }
Developer Tip: Named areas make your code incredibly readable. Even months later, you can look at the grid-template-areas block and instantly visualize the entire page structure.

Responsive Grids

Grid makes responsiveness much easier. You can redefine your entire layout inside a media query by simply changing the grid template.

/* Default: Single column for mobile */
.grid-container {
    display: grid;
    grid-template-columns: 1fr;
}

/* Tablet and Desktop: Switch to 3 columns */
@media (min-width: 768px) {
    .grid-container {
        grid-template-columns: repeat(3, 1fr); 
    }
}
Best Practice: For truly "magic" responsiveness without media queries, use: grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));. This tells the grid to pack as many 250px columns as possible into the row and resize them to fill the gaps.

Alignment and Spacing

Justify Content

justify-content aligns the entire grid within the container along the inline (horizontal) axis. This is useful when your total grid width is smaller than the parent container.

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 100px); /* Total 300px width */
    justify-content: space-around; /* Adds space between and around columns */
}

Align Items

align-items controls how the items are positioned inside their individual grid cells along the block (vertical) axis.

.grid-container {
    display: grid;
    grid-template-rows: repeat(3, 100px);
    align-items: center; /* Every item is centered vertically in its 100px row */
}

Grid Example

Here is a practical example of a simple responsive card gallery. Notice how clean the HTML remains because the layout logic is handled entirely in CSS.

<div class="grid-container">
    <div class="grid-item">Product 1</div>
    <div class="grid-item">Product 2</div>
    <div class="grid-item">Product 3</div>
    <div class="grid-item">Product 4</div>
    <div class="grid-item">Product 5</div>
    <div class="grid-item">Product 6</div>
</div>
.grid-container {
    display: grid;
    /* Creates a responsive grid that wraps automatically */
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 15px;
    padding: 10px;
}

.grid-item {
    background-color: #f4f4f4;
    border: 1px solid #ccc;
    padding: 40px 20px;
    text-align: center;
    font-family: sans-serif;
    border-radius: 8px;
}

Browser Support

CSS Grid Layout is exceptionally well-supported in all modern browsers (Chrome, Firefox, Safari, Edge). The days of worrying about Grid support are largely over, as current versions of all major browsers have fully implemented the spec.

Watch Out: Internet Explorer 11 does support an older version of the Grid spec with the -ms- prefix, but it lacks many modern features like gap and auto-placement. For most modern projects, developers now design for modern Grid and provide a simple block-level fallback for legacy browsers.

CSS Grid Layout provides a flexible and powerful way to create complex layouts, handle responsive design, and manage alignment and spacing in web pages. Mastering CSS Grid Layout can greatly enhance your ability to create modern and visually appealing designs while keeping your code clean and maintainable.