cyberangles guide

Grid Layout in CSS: A Comprehensive Tutorial

In the ever-evolving landscape of web design, creating flexible, responsive, and visually appealing layouts is a core challenge. For years, developers relied on floats, positioning, and (more recently) Flexbox to build layouts. However, these tools have limitations—especially when dealing with **two-dimensional layouts** (both rows and columns). Enter **CSS Grid Layout**, a powerful system designed from the ground up to handle rows and columns simultaneously, offering unprecedented control over page structure. CSS Grid is a *two-dimensional layout model*, meaning it can manage both horizontal and vertical space, making it ideal for complex layouts like dashboards, card grids, and multi-section web pages. Unlike Flexbox (a one-dimensional model, focused on rows *or* columns), Grid lets you define explicit rows and columns, place items precisely, and even overlap elements—all with clean, maintainable code. Whether you’re building a simple photo gallery or a sophisticated web application, mastering Grid will elevate your layout skills. This tutorial will guide you through Grid’s fundamentals, advanced features, and practical use cases, with hands-on examples to reinforce your learning.

Table of Contents

  1. Understanding CSS Grid Fundamentals

    • Grid Container vs. Grid Items
    • Grid Terminology
  2. Setting Up a Grid Container

    • display: grid
    • display: inline-grid
  3. Grid Tracks: Defining Rows and Columns

    • grid-template-rows and grid-template-columns
    • Units for Tracks: fr, px, %, auto, and minmax()
    • repeat() Function
  4. Grid Gaps: Spacing Between Items

    • gap, row-gap, and column-gap
  5. Grid Lines and Grid Areas

    • Grid Lines (Numbered and Named)
    • Grid Cells and Grid Areas
  6. Placing Grid Items

    • grid-row-start/grid-row-end and grid-column-start/grid-column-end
    • Shorthand: grid-row, grid-column, and grid-area
  7. Grid Template Areas: Visual Layout Design

  8. Auto Placement and auto-fit/auto-fill

  9. Alignment in CSS Grid

    • Aligning Grid Items: justify-items and align-items
    • Aligning Grid Tracks: justify-content and align-content
    • Aligning Individual Items: justify-self and align-self
  10. Nested Grids

  11. Responsive Grid Layouts

  12. Common Grid Patterns

    • Responsive Card Grid
    • Holy Grail Layout (Header, Sidebar, Main, Footer)
  13. Browser Support

  14. Conclusion

  15. References

1. Understanding CSS Grid Fundamentals

Before diving into code, let’s clarify key Grid concepts to avoid confusion.

Grid Container vs. Grid Items

  • Grid Container: The parent element with display: grid (or inline-grid). This enables Grid layout for its direct children.
  • Grid Items: The direct children of the grid container. Grandchildren or deeper nested elements are not grid items by default (unless nested grids are used).

Grid Terminology

  • Grid Tracks: The rows and columns of the grid. For example, a grid with 3 columns has 3 column tracks.
  • Grid Lines: The dividing lines that form the boundaries of grid tracks. They are numbered starting from 1 (e.g., a 3-column grid has 4 vertical grid lines: 1, 2, 3, 4).
  • Grid Cell: The intersection of a row and column (like a cell in a table).
  • Grid Area: A rectangular region of the grid spanning multiple cells (e.g., spanning 2 rows and 3 columns).

2. Setting Up a Grid Container

To create a grid, first define a container and set its display property to grid or inline-grid.

display: grid

This makes the container a block-level grid, taking full width of its parent (like a <div>).

Example:

<div class="grid-container">
  <div class="grid-item">Item 1</div>
  <div class="grid-item">Item 2</div>
  <div class="grid-item">Item 3</div>
</div>
.grid-container {
  display: grid; /* Enables Grid layout */
  grid-template-columns: 100px 100px 100px; /* 3 columns, 100px each */
  grid-template-rows: 50px 50px; /* 2 rows, 50px each */
}

.grid-item {
  background: #e0f7fa;
  padding: 1rem;
  border: 1px solid #80deea;
}

Output: A 2-row, 3-column grid with 6 items (3 items per row, since 2 rows × 3 columns = 6 cells).

display: inline-grid

This makes the container an inline-level grid, taking only the space needed (like an <span>). Useful for grids that should flow with text.

Example:

.inline-grid-container {
  display: inline-grid;
  grid-template-columns: 100px 100px;
  grid-template-rows: 50px;
}

3. Grid Tracks: Defining Rows and Columns

Grid tracks (rows and columns) are defined using grid-template-rows and grid-template-columns. These properties accept values that specify track sizes.

Units for Tracks

Grid supports various units to size tracks:

  • px: Fixed pixel size (e.g., 100px).
  • %: Percentage of the grid container’s size.
  • auto: Takes remaining space (expands to fit content).
  • fr: Fractional unit (distributes remaining space proportionally).
  • minmax(min, max): Defines a track size with minimum and maximum constraints (e.g., minmax(100px, 1fr)).

fr Units: The “Fraction” Unit

The fr unit is Grid’s most powerful tool for creating flexible layouts. It represents a fraction of the available space in the grid container.

Example: 3 Equal Columns

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 3 columns, equal width */
}

Here, the container’s available space is divided into 3 equal parts (1 fraction each).

repeat() Function

The repeat() function simplifies defining repeated track sizes.

Example: 4 Columns of 150px
Instead of grid-template-columns: 150px 150px 150px 150px, use:

grid-template-columns: repeat(4, 150px);

Example: Alternating Sizes

grid-template-rows: repeat(3, 50px 100px); /* 3 repetitions of 50px, 100px → 6 rows total */

4. Grid Gaps: Spacing Between Items

gap (shorthand for row-gap and column-gap) adds space between grid items (not around the container).

Syntax:

gap: <row-gap> <column-gap>; /* If only one value, row and column gaps are equal */

Example:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px; /* 20px gap between rows AND columns */
  /* Or: row-gap: 10px; column-gap: 20px; */
}

5. Grid Lines and Grid Areas

Grid Lines

Grid lines are the numbered (or named) lines that separate tracks. For a 3-column grid:

  • Vertical grid lines: 1 (left edge), 2 (between column 1 and 2), 3 (between column 2 and 3), 4 (right edge).
  • Horizontal grid lines: Numbered similarly for rows.

You can also name grid lines for clarity:

grid-template-columns: [col-start] 1fr [col-2] 1fr [col-3] 1fr [col-end];

Grid Areas

A grid area is a rectangular region spanning multiple cells. It can be defined by its start/end grid lines or named explicitly (see Section 7).

6. Placing Grid Items

By default, grid items auto-place in order (left-to-right, top-to-bottom). To manually place items, use grid-row and grid-column.

grid-row-start/grid-row-end and grid-column-start/grid-column-end

These properties define which grid lines an item spans.

Syntax:

.grid-item {
  grid-row-start: <line>;
  grid-row-end: <line>; /* Or span <number> (e.g., span 2) */
  grid-column-start: <line>;
  grid-column-end: <line>;
}

Example: Span 2 Columns

.item-2 {
  grid-column-start: 2;
  grid-column-end: 4; /* Spans from line 2 to 4 → 2 columns */
  /* Shorthand: grid-column: 2 / 4; */
}

Example: Span 2 Rows

.item-3 {
  grid-row: 1 / 3; /* Spans rows 1 to 3 → 2 rows */
}

Shorthand: grid-area
grid-area combines grid-row-start/end and grid-column-start/end:

.item {
  grid-area: <row-start> / <column-start> / <row-end> / <column-end>;
}

7. Grid Template Areas: Visual Layout Design

grid-template-areas lets you define layouts visually by naming areas and mapping items to them. It’s ideal for complex layouts like page structures.

Step 1: Define Areas in the Container

.grid-container {
  display: grid;
  grid-template-columns: 150px 1fr; /* Sidebar (150px) + Main (remaining space) */
  grid-template-rows: auto 1fr auto; /* Header (auto height), Main (flexible), Footer (auto) */
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  height: 100vh; /* Full viewport height */
}

Step 2: Assign Items to Areas

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

Output: A layout with header (spanning 2 columns), sidebar (1st column, rows 2), main (2nd column, row 2), and footer (spanning 2 columns).

8. Auto Placement and auto-fit/auto-fill

Grid auto-placements items by default, but auto-fit and auto-fill (used with repeat()) create responsive grids that adjust the number of columns based on available space.

Example: Responsive Columns with auto-fit

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}
  • auto-fit: Expands tracks to fill available space.
  • minmax(250px, 1fr): Each column is at least 250px wide, and up to 1fr (fills space).

This creates a grid that adds/removes columns as the viewport resizes (e.g., 4 columns on desktop, 2 on tablet, 1 on mobile).

9. Alignment in CSS Grid

Grid provides powerful alignment tools to control item and track positioning.

Aligning Grid Items: justify-items and align-items

  • justify-items: Aligns items horizontally (along the inline/main axis).
  • align-items: Aligns items vertically (along the block/cross axis).

Values: start (default), end, center, stretch.

Example: Center Items

.grid-container {
  justify-items: center; /* Items centered horizontally */
  align-items: center; /* Items centered vertically */
}

Aligning Grid Tracks: justify-content and align-content

These properties align the entire grid within the container when there’s extra space.

Values: start, end, center, space-around, space-between, space-evenly.

Example: Center Grid in Container

.grid-container {
  height: 500px; /* Container has fixed height */
  align-content: center; /* Grid tracks centered vertically */
}

Aligning Individual Items: justify-self and align-self

Override container alignment for specific items:

.item-2 {
  justify-self: end; /* Aligns item-2 to the right */
  align-self: center; /* Aligns item-2 vertically center */
}

10. Nested Grids

Grid items can themselves be grid containers, creating nested grids.

Example:

<div class="outer-grid">
  <div class="item">Item 1</div>
  <div class="inner-grid"> <!-- Nested grid container -->
    <div class="inner-item">Inner 1</div>
    <div class="inner-item">Inner 2</div>
  </div>
</div>
.outer-grid {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 10px;
}

.inner-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 2 columns inside the inner grid */
  gap: 5px;
}

11. Responsive Grid Layouts

Grid simplifies responsive design with media queries and minmax().

Example: Adjust Columns on Mobile

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

@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); /* Smaller min width on tablet */
  }
}

@media (max-width: 480px) {
  .grid-container {
    grid-template-columns: 1fr; /* Single column on mobile */
  }
}

12. Common Grid Patterns

Responsive Card Grid

<div class="card-grid">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
  <!-- More cards... -->
</div>
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px;
}

.card {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

Holy Grail Layout

A classic layout with header, footer, sidebar, and main content:

.holy-grail {
  display: grid;
  grid-template-columns: 150px 1fr 150px; /* Sidebar, Main, Sidebar */
  grid-template-rows: auto 1fr auto; /* Header, Main, Footer */
  grid-template-areas:
    "header header header"
    "left main right"
    "footer footer footer";
  min-height: 100vh; /* Full viewport height */
}

.header { grid-area: header; }
.left { grid-area: left; }
.main { grid-area: main; }
.right { grid-area: right; }
.footer { grid-area: footer; }

/* Mobile: Stack all sections */
@media (max-width: 768px) {
  .holy-grail {
    grid-template-columns: 1fr;
    grid-template-areas:
      "header"
      "left"
      "main"
      "right"
      "footer";
  }
}

13. Browser Support

CSS Grid is supported in all modern browsers: Chrome, Firefox, Safari, Edge, and Opera. IE11 has partial support with vendor prefixes (-ms-), but it’s rarely needed today. Check caniuse.com for details.

14. Conclusion

CSS Grid Layout is a game-changer for web layout design. Its two-dimensional nature, flexible track sizing, and powerful alignment tools make it the go-to choice for everything from simple card grids to complex web applications. By mastering Grid, you’ll write cleaner, more maintainable code and build layouts that adapt seamlessly to any screen size.

Practice is key! Experiment with the examples above, tweak values, and explore nested grids or advanced patterns. The web is your canvas—Grid is your brush.

15. References