MGU Computer Science Series — Web Development: HTML, CSS, and JavaScript
Part III: CSS — Style and Layout
Tracks · Fractional Units · Gaps · Placement · Named Areas
Chapter 16 of 30
16
MGU Computer Science Series  ·  Web Development: HTML, CSS, and JavaScript  ·  Library Textbook Edition

Chapter 16:
Grid Layout

Building two-dimensional page layouts with CSS Grid — containers, tracks, fractional space, gaps, responsive sizing, and precise item placement

■ Part III of VII ■

■ 10 Sections  •  Chapter 16 of 30 ■

Builds on Chapter 15 (Flexbox) — assumes comfort with the box model and basic CSS selectors

Chapter Introduction and Learning Objectives

Chapter 15 introduced Flexbox as a one-dimensional layout system for rows and columns. Flexbox is excellent for navigation bars, card rows, centered content, and similar single-axis arrangements. But many layouts on the web are genuinely two-dimensional: they need rows and columns working together at the same time. CSS Grid is the layout system built for that job.

This chapter teaches CSS Grid from the ground up. You will learn how Grid containers and Grid items relate to each other, how to define rows and columns using tracks, how to use fractional units to distribute space proportionally, how to control gaps, and how to place items precisely within a Grid. You will also learn when to reach for Grid and when Flexbox is the better tool. By the end of this chapter, you will be able to build image galleries, page skeletons, dashboard cards, and multi-column content layouts using Grid — and you will understand how Grid and Flexbox complement each other in the same project.

Opening Question

Imagine a web page with a header at the top, a sidebar on one side, a main content area beside it, and a footer at the bottom — all positioned in relation to each other, not just stacked top to bottom. Flexbox can approximate this with effort, but it was designed to manage a single row or a single column at a time. What if a layout system could let you define rows and columns together, on one container, and then drop any element into any cell of that structure? That system is CSS Grid, and that is exactly what this chapter teaches you to build.

10Sections
12Objectives
25Key Terms
30Total Chapters

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Explain why CSS Grid exists and what kinds of layout problems it solves better than Flexbox.
  2. 2Distinguish a Grid container from a Grid item and explain how applying display: grid changes a page.
  3. 3Define track, grid line, cell, and grid area, and explain the difference between explicit and implicit tracks.
  4. 4Use grid-template-columns and grid-template-rows to define the structure of a grid.
  5. 5Use the fr unit to distribute space proportionally between columns and rows.
  6. 6Use gap to control spacing between rows and columns without affecting outer spacing.
  7. 7Use repeat() and minmax() together to build responsive grids without writing media queries.
  8. 8Place Grid items explicitly using grid-column, grid-row, line numbers, and the span keyword.
  9. 9Build full page layouts using named grid areas with grid-template-areas and grid-area.
  10. 10Decide, for a given layout problem, whether Grid or Flexbox is the better tool — and use both together in the same project.
  11. 11Identify and correct common CSS Grid mistakes, including missing display: grid and misplaced properties.
  12. 12Build a complete, responsive card gallery and a full page skeleton using CSS Grid.

Sections at a Glance

Sections 16.1 – 16.3
The Case for Grid: Why It Exists and How It Is Built
Containers · Items · Tracks · Lines · Cells

Why Grid Exists

Before CSS Grid, developers built two-dimensional layouts using floats, tables repurposed as layout tools, and complicated hacks with absolute positioning. These approaches were fragile. A layout that worked in one browser often broke in another. Pages required deeply nested HTML just to create a column. Changing the layout meant rewriting large amounts of HTML.

Flexbox improved this situation significantly when it arrived. But Flexbox was designed to work along a single axis at a time. It does rows or columns, not rows and columns simultaneously. When designers needed true grid-based layouts — a page with a sidebar, main content, and footer all positioned in relation to each other — Flexbox required workarounds.

CSS Grid was designed specifically to solve two-dimensional layout. It lets you define both rows and columns on a single container, then place any child element into any cell in that grid. The HTML can stay clean. The layout logic moves into CSS where it belongs. Grid became fully supported across all major browsers starting around 2017 and is now one of the most important layout tools in CSS. Learning it is not optional for modern web development.

Good Fit
What Grid Is Good At
  • Page-level layout: header, navigation, sidebar, main content, footer
  • Card grids and image galleries with consistent rows and columns
  • Dashboard layouts with multiple panels
  • Any layout needing items positioned relative to rows and columns at once
Poor Fit
What Grid Is Less Suited For
  • Simple single-row navigation bars (Flexbox is usually simpler)
  • A list of items that should wrap freely without a strict column count
  • Centering a single item (Flexbox or a simple margin trick is less verbose)
Study Note

You will use both Grid and Flexbox in the same project. They are not competitors. They are tools for different problems, and this chapter will return to that distinction in Section 16.10.

Grid Containers and Grid Items

Like Flexbox, CSS Grid is applied to a container element. The container becomes a Grid container. Its direct children automatically become Grid items. To make an element a Grid container, you apply one CSS property: display: grid.

HTML
<div class="gallery">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
  <div class="card">Card 4</div>
  <div class="card">Card 5</div>
  <div class="card">Card 6</div>
</div>
CSS
.gallery {
  display: grid;
}

At this point, nothing visible has changed yet. The div.gallery is now a Grid container, and the six .card divs are Grid items. But without defining columns or rows, the browser stacks everything in a single column exactly as block elements normally would. The visual change comes when you define the structure of the grid, starting in Section 16.4.

The Mental Model

The container defines structure. The items flow into it. The Grid container decides how many columns exist, how many rows exist, how large each track is, and how much space goes between items. Grid items respond to that structure. By default they flow into cells automatically from left to right and top to bottom, but you can also give individual items instructions about exactly where they should sit, as you will see in Section 16.9.

Rows, Columns, and Tracks

The building blocks of a CSS Grid are tracks. A track is a single row or a single column in the grid. When you define a grid, you are defining its tracks. The space between tracks is the gap. The intersections of rows and columns create cells. A rectangular area covering one or more cells is called a grid area.

Visualizing the grid is important. Imagine graph paper. The horizontal lines create rows. The vertical lines create columns. Each square on the paper is a cell. An item can occupy one cell or span multiple adjacent cells.

Grid also gives you access to grid lines — the dividing lines between tracks. They are numbered starting from 1. A three-column grid has four vertical grid lines: line 1 on the left edge, line 2 between the first and second columns, line 3 between the second and third columns, and line 4 on the right edge. Understanding grid lines becomes important when placing items explicitly in Section 16.9.

Explicit Versus Implicit Tracks

When you define columns and rows in your CSS, those are called explicit tracks. You have deliberately told the browser how many tracks to create and how large they should be.

When items overflow the explicit grid — meaning you defined three columns but have enough items to need more rows than you explicitly defined — the browser creates additional rows automatically. These are called implicit tracks. You can control the size of implicit tracks using the grid-auto-rows property, covered in Section 16.5. For most beginner layouts, thinking in terms of explicit tracks is enough.

Sections 16.4 – 16.7
Defining the Grid: Columns, Rows, Gaps, and Fractional Space
grid-template-columns · grid-template-rows · gap · The fr Unit

grid-template-columns

The grid-template-columns property defines how many columns the grid has and how wide each column should be. The value is a space-separated list of sizes. Each size you provide creates one column. Two sizes create a two-column grid. Four sizes create a four-column grid.

CSS
.gallery {
  display: grid;
  grid-template-columns: 200px 200px 200px;
}

This creates a three-column grid where each column is exactly 200 pixels wide. Items flow into the columns from left to right. When three items have filled the first row, the next item starts a new row automatically. You can use any CSS length unit for column sizes: px, em, rem, percentages, and the fractional unit fr (covered in Section 16.7).

Different Column Widths

Columns do not have to be the same size. A sidebar layout might use a wide main column and a narrower sidebar column:

CSS
.page-layout {
  display: grid;
  grid-template-columns: 200px 1fr;
}

This example uses two different units on purpose. The sidebar is 200 pixels fixed. The 1fr means the remaining space goes to the main content area. The fr unit is one of Grid's most powerful features and gets its own full section later in the chapter.

Worked Example
A three-column card layout
  • HTMLSix <article class="card"> elements live inside a <div class="card-grid">.
  • CSS.card-grid { display: grid; grid-template-columns: 300px 300px 300px; }
  • ResultThe six cards arrange themselves into two rows of three columns each. The browser handles the row creation automatically because three columns were defined; it infers that new rows are needed after every three items.

grid-template-rows

The grid-template-rows property defines explicit row heights. It works the same way as grid-template-columns but controls horizontal tracks instead of vertical ones.

CSS
.dashboard {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 200px 400px;
}

This creates a three-column, two-row grid. The first row is 200 pixels tall. The second row is 400 pixels tall. In many practical layouts, you do not need to define row heights explicitly. If you do not define rows, the browser creates them implicitly as content overflows the explicit grid, and each row takes the height of its tallest item. This natural behavior is usually what you want.

grid-auto-rows

When the browser creates implicit rows automatically, you can control their default height with grid-auto-rows:

CSS
.card-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-auto-rows: 250px;
}

Now every automatically created row will be 250 pixels tall, giving the grid a uniform cell height regardless of how many rows the content requires. A more flexible approach uses minmax(), covered fully in Section 16.8:

CSS
.card-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-auto-rows: minmax(200px, auto);
}
Reading This Value

This tells the browser: each row should be at least 200 pixels tall, but it can grow larger if the content inside it is taller. This is a very common pattern in gallery and card layouts.

Gaps

Like Flexbox, CSS Grid uses the gap property to control the space between tracks. The gap appears between columns and between rows, but never on the outer edges of the grid.

CSS
.card-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 1.5rem;
}

This adds 1.5rem of space between every row and every column. If you need different horizontal and vertical spacing, you can provide two values. The first value controls the row gap; the second controls the column gap:

CSS
.card-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 2rem 1rem;
}

Here the rows have 2rem of space between them, and the columns have 1rem of space between them. You can also use the longhand properties row-gap and column-gap individually, though the shorthand gap is preferred for most use cases.

Don't Confuse Gap and Padding

gap does not add space outside the grid itself. If you need space around the outside of the grid, use padding on the container: gap: 1.5rem; padding: 2rem; gives the cards breathing room between each other from gap, and breathing room around the whole grid from padding.

Fractional Units

The fr unit is unique to CSS Grid. It stands for fraction of the available space. When you use fr units in grid-template-columns, the browser calculates how much space is left after fixed-size columns and gaps have been placed, then divides that remaining space among the fractional columns according to their proportions.

Equal-Width Columns

CSS
.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

Three columns, each getting one-third of the total available space. If the container is 900 pixels wide, each column is 300 pixels wide. If the container is 600 pixels wide, each column is 200 pixels wide. The columns grow and shrink with the container automatically — already a significant improvement over writing 33.33% and dealing with rounding errors.

Unequal Proportions

CSS
.layout {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
}

The middle column gets twice as much space as each side column. In a 900-pixel container, the middle column is 450 pixels wide and each side column is 225 pixels wide. A common main-content-plus-sidebar proportion is grid-template-columns: 3fr 1fr; — the main content gets three-quarters of the available space, and the sidebar gets one-quarter.

Mixing Fixed and Fractional Units

CSS
.layout {
  display: grid;
  grid-template-columns: 250px 1fr;
}

One of the most powerful patterns in Grid is mixing px (or rem) with fr. The sidebar is always 250 pixels wide. The main content area fills all remaining space. This is a much cleaner way to write a classic sidebar layout than the float-based approaches of the past. When the browser calculates the 1fr, it first subtracts the 250 pixels of the fixed column (and any gaps) from the total container width, then assigns the remainder to the 1fr column.

Sections 16.8 – 16.10
Responsive Grids and Precise Placement
repeat() · minmax() · Explicit Placement · Named Areas · Full Page Layouts

repeat() and minmax() at an Introductory Level

Two CSS Grid functions are worth learning early because they appear in nearly every real project: repeat() and minmax().

repeat()

The repeat() function lets you avoid writing the same track size multiple times. Instead of writing grid-template-columns: 1fr 1fr 1fr 1fr;, you write:

CSS
grid-template-columns: repeat(4, 1fr);

The first argument to repeat() is the number of times to repeat. The second argument is the track size (or sizes) to repeat. These produce an equivalent four-column equal-width grid. repeat() becomes especially useful with the auto-fill keyword, which allows the browser to create as many columns as will fit in the container:

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, 250px);
  gap: 1.5rem;
}

With auto-fill, the browser creates as many 250px columns as will fit in the available space and wraps excess items to new rows. This creates a naturally responsive gallery without media queries — if the viewport is wide, you get many columns; if it is narrow, you get fewer. The difference between auto-fill and auto-fit is subtle and involves how empty space is handled at the end of a row. For most beginners, auto-fill is the safer default.

minmax()

The minmax() function defines a size range for a track. It takes two arguments: a minimum size and a maximum size.

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(3, minmax(200px, 1fr));
  gap: 1.5rem;
}

Each column is at least 200 pixels wide but will grow up to an equal share of available space (1fr). This prevents columns from collapsing to an unreadably narrow width while still allowing them to expand naturally. A very common professional pattern combines auto-fill with minmax():

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.5rem;
}
Read This Pattern Carefully

Create as many columns as will fit, where each column is at least 250 pixels wide but can grow to fill equal shares of available space. This single line creates a fully responsive card grid that adjusts its number of columns based on viewport width with no media queries needed. You will use this pattern often — it appears again in the Mini-Project at the end of this chapter.

Placing Grid Items

By default, Grid items flow automatically into the grid from left to right and top to bottom, filling each cell in order. This automatic placement is called auto-placement and is exactly what you want for galleries, card grids, and other uniform layouts. But Grid also allows you to place items explicitly into specific positions. This is what makes Grid so powerful for page-level layouts.

Grid Lines as Addresses

Every Grid container has numbered lines. For columns, line 1 is the left edge. For rows, line 1 is the top edge. The last line number is one more than the number of tracks. A three-column grid has vertical lines 1, 2, 3, and 4. A two-row grid has horizontal lines 1, 2, and 3.

You can tell a Grid item where to start and end using these line numbers:

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

This places the item starting at column line 1 and ending at column line 3 — meaning it spans two columns. It starts at row line 1 and ends at row line 2 — meaning it occupies the first row.

The span Keyword

Instead of specifying end line numbers, you can use the span keyword to indicate how many tracks an item should cross:

CSS
.featured {
  grid-column: span 2;
}

This tells the featured item to span two columns, starting wherever the auto-placement algorithm puts it.

A Practical Placement Example

Consider a simple page where you want a header that spans the full width, a main content area, and a sidebar:

CSS
.page {
  display: grid;
  grid-template-columns: 1fr 300px;
  grid-template-rows: auto 1fr auto;
  gap: 1.5rem;
  min-height: 100vh;
}

.site-header {
  grid-column: 1 / 3;
}

.site-footer {
  grid-column: 1 / 3;
}

The header and footer span both columns using grid-column: 1 / 3. The main content and sidebar each occupy one column in the middle row, placed there automatically by the browser. This pattern — a two-column layout with a full-width header and footer — is one of the most common page structures on the web, and Grid makes it straightforward.

Named Grid Areas

Grid also allows you to name areas and assign items to those names, which many developers find easier to read than line numbers:

CSS
.page {
  display: grid;
  grid-template-columns: 1fr 300px;
  grid-template-areas:
    "header  header"
    "content sidebar"
    "footer  footer";
  gap: 1.5rem;
}

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

The grid-template-areas property uses quoted strings where each string represents a row. Each word in the string represents a column. When the same name appears in multiple cells, the item stretches across those cells. A period . represents an empty cell. Named grid areas make layout intentions explicit and readable — particularly helpful in large projects where the layout code needs to be easy to understand weeks or months later.

Building Page Layouts with Grid

Now you will put these concepts together into a realistic full-page layout. This example builds the core skeleton of the Student Learning Site's main layout: a full-width site header, a full-width navigation below it, a main content area on the left, a 280-pixel sidebar on the right, and a full-width footer.

HTML
<div class="page-wrapper">

  <header class="site-header">
    <p class="site-name">Student Learning Site</p>
  </header>

  <nav class="site-nav">
    <ul>
      <li><a href="index.html">Home</a></li>
      <li><a href="about.html">About</a></li>
      <li><a href="lessons.html" aria-current="page">Lessons</a></li>
      <li><a href="resources.html">Resources</a></li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
  </nav>

  <main class="main-content">
    <h1>Lessons</h1>
    <p>Browse the lessons below to begin learning.</p>

    <div class="lesson-grid">
      <article class="lesson-card">
        <h2>Lesson 1: HTML Foundations</h2>
        <p>Learn how HTML gives structure to web pages.</p>
      </article>
      <article class="lesson-card">
        <h2>Lesson 2: CSS Basics</h2>
        <p>Learn how CSS controls visual presentation.</p>
      </article>
      <article class="lesson-card">
        <h2>Lesson 3: CSS Layout</h2>
        <p>Learn Flexbox, Grid, and responsive design.</p>
      </article>
    </div>
  </main>

  <aside class="sidebar">
    <h2>Quick Links</h2>
    <ul>
      <li><a href="#">Getting Started Guide</a></li>
      <li><a href="#">HTML Cheat Sheet</a></li>
    </ul>
  </aside>

  <footer class="site-footer">
    <p>&copy; 2025 Student Learning Site. All rights reserved.</p>
  </footer>

</div>
CSS
.page-wrapper {
  display: grid;
  grid-template-columns: 1fr 280px;
  grid-template-areas:
    "header  header"
    "nav     nav"
    "content sidebar"
    "footer  footer";
  gap: 2rem;
  max-width: 1100px;
  margin: 0 auto;
  padding: 0 2rem;
}

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

.site-nav ul {
  display: flex;
  gap: 1.25rem;
  list-style: none;
}

.lesson-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 1.25rem;
}

.sidebar {
  align-self: start;
}

Walk through the important decisions in this code. The .page-wrapper is the Grid container. It has two columns: the main content area gets 1fr (all available space), and the sidebar gets a fixed 280px. The grid-template-areas property names four rows of layout. The header and nav each span both columns. The content and sidebar sit side by side in the middle row. The footer spans both columns again at the bottom. Each semantic element then receives its grid-area assignment in a clean, readable block.

Notice that the .lesson-grid inside the main content is itself a second Grid using repeat(auto-fill, minmax(240px, 1fr)). This is a nested Grid. The outer Grid controls the overall page structure. The inner Grid controls the lesson card layout. Nesting Grid inside Grid is normal and common.

The sidebar uses align-self: start so it does not stretch to match the full height of the main content column. Without this, the sidebar would expand to fill all available vertical space. align-self: start keeps it flush with the top.

When to Use Grid and When to Use Flexbox

Both Grid and Flexbox are essential. Knowing which to use comes with practice, but here are reliable starting rules.

Choose Grid
Use Grid When...
  • You need both rows and columns controlled at the same time
  • You are building a page-level layout (header, sidebar, footer)
  • You are building a gallery or card grid where items must align in rows and columns
  • You want to place items into specific named areas of the page
  • You need a fixed-width sidebar next to flexible main content
Choose Flexbox
Use Flexbox When...
  • You are arranging items along a single direction (a navigation bar, a row of icons)
  • You want items to wrap naturally without strict column alignment across rows
  • You are aligning items inside a card or small component
  • You need to push one item to the far end of a row (margin-left: auto)
  • You have a small group of items where row-versus-column tracking is not important
Using Both Is Correct

A page built with Grid for its overall layout can have a Flexbox navigation inside the header, Flexbox buttons inside each card, and a Flexbox-centered footer. They solve different problems and work well together — exactly as shown in the page layout example above, where the outer structure is Grid and the .site-nav ul is Flexbox.

Common Grid Mistakes

Mistake 1 — Forgetting display: grid

You can write grid-template-columns and nothing will happen unless you have also applied display: grid to the container. Always verify the container has the Grid context.

Mistake 2 — Properties on the Wrong Element

grid-template-columns and grid-template-rows go on the container. Properties like grid-column and grid-row go on individual items. Mixing these up is a very common early mistake. If columns are not forming, check whether your properties are on the right element.

Mistake 3 — Forgetting Gaps

A grid with no gap will have items sitting directly against each other with no breathing room. Always add gap to avoid cramped layouts. Even gap: 1rem makes a significant visual difference.

Mistake 4 — Fixed Pixels Where fr Would Be Better

If you write grid-template-columns: 300px 300px 300px;, the grid will overflow its container on narrow screens. Using 1fr 1fr 1fr or repeat(3, 1fr) instead allows columns to shrink proportionally. Use fixed pixel sizes only when you specifically need a column to remain a constant width.

Mistake 5 — Expecting Automatic Centering

Grid places items into cells, but it does not center them within those cells by default. To center content inside a grid item, use display: flex; align-items: center; justify-content: center; on the item itself, or use place-items: center on the grid container to center all items in their cells.

Mistake 6 — Mismatched Named Areas

If you define named areas in grid-template-areas but forget to assign the corresponding grid-area property to an element, that element will fall outside the named layout and cause unexpected visual results. Make sure every named area has a matching grid-area assignment on the correct HTML element.

Debugging Grid Layouts

Browser developer tools have excellent Grid debugging features. When you inspect a Grid container in the Elements panel, Firefox shows an overlay with column and row numbers drawn directly on the page, including gaps and track sizes — the most detailed Grid debugger available in any browser. Chrome and Edge show a Grid badge next to Grid containers in the Elements panel; clicking the badge toggles a visual overlay showing the grid lines.

Debugging Workflow
Investigating a Grid problem
  • InspectOpen developer tools and inspect the container element.
  • ToggleLook for the Grid badge or overlay toggle and enable it.
  • CompareCompare what the overlay shows with what your CSS says.
  • VerifyCheck whether the container has display: grid, whether track sizes make sense, and whether items are placed on the correct grid lines or areas.
A High-Value Habit

Using the Grid overlay in Firefox for a complicated layout is one of the most productive debugging actions you can take. It shows you immediately whether your CSS is creating the structure you intended.

Chapter Summary

Key Terms

CSS Grid
A CSS layout system that controls both rows and columns simultaneously using a grid container and grid items.
Grid container
An element with display: grid applied. It defines the grid structure.
Grid item
A direct child of a Grid container. Items are placed into the grid automatically or explicitly.
Track
A single row or column in a Grid layout.
Grid line
A dividing line between tracks. Lines are numbered starting from 1.
Cell
The intersection of a single row track and a single column track in a grid.
Grid area
A rectangular region of the grid that can span one or more cells.
Explicit track
A track defined deliberately in CSS using grid-template-columns or grid-template-rows.
Implicit track
A track created automatically by the browser when items overflow the explicit grid.
grid-template-columns
The CSS property that defines how many columns a grid has and how wide each column is.
grid-template-rows
The CSS property that defines how many explicit rows a grid has and how tall each row is.
grid-auto-rows
The CSS property that sets the height of implicitly created rows.
gap
The CSS property that sets the space between grid tracks (rows and columns).
fr unit
A fractional unit unique to CSS Grid. One fr represents a share of the remaining available space.
repeat()
A CSS Grid function that repeats a track definition a specified number of times. Also accepts auto-fill and auto-fit.
minmax()
A CSS Grid function that sets a minimum and maximum size for a track, allowing it to be flexible but bounded.
auto-fill
A keyword used with repeat() that tells the browser to create as many tracks as will fit in the container.
Auto-placement
The default behavior where Grid items are placed into cells in order from left to right and top to bottom without explicit positioning instructions.
grid-column
A property applied to a Grid item that specifies which column lines the item starts and ends at.
grid-row
A property applied to a Grid item that specifies which row lines the item starts and ends at.
span
A keyword used with grid-column or grid-row to indicate how many tracks an item should cross.
grid-template-areas
A property on the Grid container that assigns readable names to areas of the grid.
grid-area
A property on a Grid item that assigns it to a named area defined in grid-template-areas.
align-self: start
A property applied to a Grid item that prevents it from stretching to fill the full height of its row and instead aligns it with the top.
Nested Grid
A Grid container placed inside another Grid container. Used to control layout at different scales within the same page.

Concept Check

Answer these questions before beginning the full review questions. They check basic understanding, not deep analysis.

  1. In your own words, what does display: grid do to an element and its direct children?
  2. What is a track? How is a track different from a cell?
  3. What does the fr unit represent, and why is it different from a fixed unit like px?
  4. What is the difference between gap and padding on a Grid container?
  5. What problem does repeat(auto-fill, minmax(250px, 1fr)) solve without needing a media query?
  6. What is the difference between auto-placement and explicit placement of a Grid item?
  7. Name one situation where Flexbox is a better choice than Grid, and one where Grid is a better choice than Flexbox.
PracticeCode Reading

Study each example carefully. Before looking at the questions, trace through the code and describe what you expect to see.

Code Reading 16-A

CSS + HTML
.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  gap: 1rem;
}

<div class="container">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
</div>
  1. How many columns does this grid have?
  2. How many rows will the browser create to hold all six items?
  3. Which items will appear in the first row?
  4. What does 1fr 1fr 1fr 1fr mean in terms of width?
  5. Will there be space between the items? Between the items and the container edges?

Code Reading 16-B

CSS
.layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-areas:
    "header  header"
    "sidebar content"
    "footer  footer";
  gap: 1.5rem;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.footer  { grid-area: footer; }
  1. How many columns does this layout have?
  2. How wide is the sidebar column?
  3. How wide is the content column relative to the container?
  4. How many rows are in the explicit grid?
  5. Which elements span both columns?
  6. What would happen if you removed grid-area: header from the .header rule?

Code Reading 16-C

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1.25rem;
}
  1. Is the number of columns fixed or flexible in this grid?
  2. What is the minimum width of each column?
  3. What is the maximum width of each column?
  4. If the container is 800 pixels wide and the gap is 1.25rem (about 20px), approximately how many columns will the browser create?
  5. What happens to the column count when the viewport becomes narrower?
PracticeGrid Diagram Practice

For each exercise, draw or describe the grid structure. Label the rows, columns, tracks, and gaps.

Exercise 16-D1

CSS — container is 900px wide
display: grid;
grid-template-columns: 1fr 2fr 1fr;
gap: 20px;

Describe how wide each column is. (Hint: 900px minus two 20px gaps leaves 860px to distribute. The first 1fr gets one-quarter, the 2fr gets two-quarters, the last 1fr gets one-quarter.)

Exercise 16-D2

CSS — six cards are placed into this grid
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 180px;
gap: 1rem;

How many rows form? How tall is each row?

Exercise 16-D3

CSS
.page {
  display: grid;
  grid-template-columns: 1fr 250px;
  grid-template-areas:
    "header  header"
    "main    aside"
    "main    aside"
    "footer  footer";
}

Describe the visual layout produced. Which elements are wide? Which are narrow? How does the main content compare in height to the aside?

PracticeFlexbox Versus Grid Questions

For each scenario, decide whether Flexbox or Grid is the better choice. Explain your reasoning.

  1. You want to build a horizontal navigation bar with five links spaced evenly across the top of the page.
  2. You want to build a page with a header, a sidebar, a main content area, and a footer, all positioned relative to each other.
  3. You want to display eight product cards in a responsive grid that automatically adjusts its number of columns based on screen width.
  4. You want to center a single button horizontally and vertically inside a banner section.
  5. You want to lay out a hero section with an image on the left and a paragraph of text on the right, both vertically centered relative to each other.
  6. You want to build an image gallery where every photo cell is the same size and photos wrap naturally to new rows as the container narrows.
DebuggingLayout Debugging

Each example below has a problem. Identify the mistake and write a corrected version.

Debug 16-E1

CSS
.card {
  grid-template-columns: 1fr 1fr 1fr;
  gap: 1rem;
}

There are six child elements inside .card but they are not forming a three-column grid. What is missing?

Debug 16-E2

CSS
.page {
  display: grid;
  grid-template-columns: 250px 1fr;
  grid-template-areas:
    "nav nav"
    "sidebar main"
    "footer footer";
}

.sidebar      { grid-area: sidebar; }
.main-content { grid-area: main-content; }
.site-nav     { grid-area: nav; }
.site-footer  { grid-area: footer; }

The main content area is not appearing in the correct grid area. What is the problem?

Debug 16-E3

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  gap: 1rem;
}

On a wide screen the gallery looks fine. On a narrow mobile screen, cards overflow outside the container. Which change would fix this without adding media queries?

Debug 16-E4

CSS
.layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas:
    "header sidebar"
    "main   sidebar"
    "footer footer";
}

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

A student wants the header to span both columns. The grid-template-areas declaration shows "header sidebar" in the first row, meaning the header only takes one column. How should grid-template-areas be changed so the header spans both columns?

BuildShort Build Tasks

Complete each task in a code editor. Test in the browser before moving on.

  1. Task 16-F1. Create an HTML file with eight <article> elements inside a <section class="cards">. Write CSS that makes .cards a three-column grid using repeat(3, 1fr) with a gap of 1.25rem. Give each article a background color, padding, and border radius.
  2. Task 16-F2. Add grid-auto-rows: minmax(150px, auto) to the card grid from Task 16-F1. Add varying amounts of text to different cards to see how the row height responds. Observe that shorter and taller cards in the same row all match the tallest card in that row.
  3. Task 16-F3. Build a two-column layout. The left column should be 1fr wide and contain a heading and two paragraphs. The right column should be 280px wide and contain a list of links inside an <aside>. Add align-self: start to the aside so it does not stretch to full height.
  4. Task 16-F4. Convert the two-column layout from Task 16-F3 to use grid-template-areas. Name the areas main and sidebar. Assign them using grid-area on the relevant elements.
  5. Task 16-F5. Build a gallery of twelve <figure> elements, each containing an <img> (or a colored placeholder div) and a <figcaption>. Use repeat(auto-fill, minmax(220px, 1fr)) for the columns and a gap of 1rem. Resize the browser window and observe how the column count changes.
Mini-Project: Responsive Gallery
Build a complete gallery page for the Student Learning Site
Page Content
  • A site header with the site name
  • A navigation menu (Flexbox, linking to other pages)
  • A page heading: "Lesson Gallery"
  • A short introductory paragraph
  • A gallery of at least eight cards using repeat(auto-fill, minmax(240px, 1fr))
  • Each card has a title, a short description, and a label such as "HTML", "CSS", or "JavaScript"
  • A full-width footer
Technical Requirements
  • Use CSS custom properties for colors, spacing, and the sidebar width if applicable
  • Use named grid areas for the page structure
  • Use a nested inner grid for the card gallery
  • No inline styles — all CSS lives in css/main.css
  • Validate the HTML
  • Check that the layout looks reasonable at both narrow (360px) and wide (1200px+) viewport widths
Mini-Project Accessibility Check
Review the completed Mini-Project against each item below
  • The page has exactly one <h1> that describes the page content.
  • The gallery cards use <article> or another appropriate semantic element.
  • All card headings use <h2> (or another appropriate level) and follow a logical heading order.
  • Any images used have meaningful alt text, or alt="" if purely decorative.
  • Navigation links are descriptive, and the current page's link has aria-current="page".
  • The color contrast between text and background is sufficient for readability.
  • The page can be navigated using only the keyboard (Tab key to move between links).
Mixed ReviewCumulative Practice

These questions draw on material from earlier chapters.

  1. From Chapter 14: A card has padding: 1rem, border: 2px solid #ccc, and a defined width: 300px. By default, what is the total rendered width of the card, and how does box-sizing: border-box change this?
  2. From Chapter 15: You have a navigation bar built with Flexbox. The logo is on the left and the links are on the right. Write the CSS to push the links to the far right without using position: absolute.
  3. From Chapter 13: You are choosing between 1rem and 1em for font size on paragraph text. What is the difference, and which is generally safer for consistent results across nested elements?
  4. From Chapter 12: A heading has a type selector h2 { color: gray; } and a class selector .highlight { color: blue; }. The heading element in the HTML has class="highlight". Which color wins? Why?
  5. From Chapter 11: You have written some styles in a <style> tag inside the <head>. You later move those styles to an external main.css file and link it properly. Should the styles still work? What are the advantages of the external file approach?
ReviewReview Questions

Recall and Vocabulary

  1. What is the difference between a Grid container and a Grid item?
  2. Define "track" in your own words. How does a track differ from a "cell"?
  3. What does grid-template-columns control? Give an example with three columns of different sizes.
  4. What is the difference between an explicit track and an implicit track?
  5. What does the fr unit represent, and how is it different from a percentage?
  6. What is the purpose of the gap property in a Grid layout?
  7. What do repeat() and minmax() each do? Why are they often used together?
  8. What is the difference between grid-template-areas and grid-area?

Understanding and Explanation

  1. Explain why Flexbox is not well suited to a layout with both a sidebar and a header that need to be controlled in two dimensions at once.
  2. The chapter says items "flow into the grid automatically by default." Explain what this means and when you would want to override it.
  3. Explain in your own words why repeat(auto-fill, minmax(250px, 1fr)) creates a responsive layout without any media queries.
  4. Why does align-self: start matter for a sidebar inside a Grid layout? What happens if it is omitted?
  5. Explain the difference between using grid-column: 1 / 3 and grid-column: span 2. Are there situations where these produce the same result?
  6. Why is it usually better to use named grid areas instead of grid-line numbers for a full page layout?

Application and Analysis

  1. A designer wants a three-column card grid where the middle column is always twice as wide as the side columns, and the whole grid should be 1000px max. Write the CSS for grid-template-columns that achieves this.
  2. A student writes grid-template-columns: 300px 300px 300px; gap: 1rem; inside a container that is only 700px wide on a phone screen. Identify the problem this will cause and rewrite the CSS to fix it responsively.
  3. Look at the "Building Page Layouts with Grid" example in Section 16.10. Identify which CSS rule is responsible for making the header span both columns, and explain why removing that rule would break the layout.
  4. A page has a Grid container with two columns and three named rows (header, content, footer), but the sidebar element does not have a grid-area assigned. Predict what will happen to the sidebar in the rendered page.

Design and Synthesis

  1. Design, in CSS, a layout using grid-template-areas for a blog post page that includes a full-width header, a full-width title section below it, a main article column, a related-posts sidebar, and a full-width footer. Write the grid-template-areas declaration and the grid-area assignments.
  2. Write a short paragraph, suitable for a beginner who has only used Flexbox, explaining why they might still need to learn Grid. Use at least one concrete layout example in your explanation.
Chapter 16 Checklist
Use this to confirm your understanding before moving to Chapter 17
Concepts
  • I can explain why CSS Grid exists and what problems it solves better than Flexbox.
  • I can distinguish a Grid container from a Grid item.
  • I can define track, grid line, cell, and grid area.
  • I can explain the difference between explicit and implicit tracks.
  • I can use grid-template-columns and grid-template-rows to define a grid's structure.
  • I can use the fr unit to create equal and unequal column proportions.
  • I can use gap to control spacing without affecting the outer edges of the grid.
Building Layouts
  • I can use repeat() and minmax() together to build a responsive gallery with no media queries.
  • I can place a Grid item explicitly using line numbers or the span keyword.
  • I can build a full page layout using named grid areas with grid-template-areas and grid-area.
  • I can build a nested grid (a grid inside a grid).
  • I can decide whether Grid or Flexbox fits a given layout problem.
Debugging
  • I know to check for a missing display: grid when a layout is not forming.
  • I know that grid-template-columns/grid-template-rows belong on the container, while grid-column/grid-row belong on items.
  • I can use browser developer tools to view a Grid overlay and compare it against my CSS.
Preview — Chapter 17
Responsive Design and Media Queries

Chapter 17 covers responsive design and media queries. You now know how to build Grid layouts that use fr units and auto-fill to adapt naturally to different widths. Chapter 17 takes the next step: writing media queries that change layout, typography, spacing, and navigation at specific breakpoints. You will also learn mobile-first design — the practice of writing styles for small screens first and adding complexity for larger screens. By the end of Chapter 17, your Student Learning Site pages will look and work well on phones, tablets, and large monitors.

MGU Library Connection
  • Web Development: HTML, CSS, and JavaScript — Appendix E: CSS Layout Reference
  • Web Development: HTML, CSS, and JavaScript — Appendix M: Glossary
  • Companion resource: Flexbox Guide
  • Companion resource: Grid Guide
  • Companion resource: Responsive Design Checklist
  • Next section: Chapter 17 — Responsive Design and Media Queries
  • MGU Digital Literacy — background reading on accessible, adaptable web layout