Define Grid Tracks

The events pages are lined up now, but the menu, the sign-up notice and the seed tags each run along one line at a time. Rosa’s next request needs two directions at once. She’d like the seven Coming Up cards on the events page in three columns, so visitors see the whole spring season at a glance instead of scrolling past a long stack.

Wrapping flex items could make rows of cards, but the browser lays out each wrapped line on its own, so cards in different rows don’t share column widths. Grid lays out rows and columns together.

In this lesson, you’ll define a grid’s columns, size them with the fr unit, space them with gap, and check the result in DevTools’ grid overlay. Start with the parent that holds the cards.

Turn the Card List Into a Grid

The cards’ parent is .event-list, the wrapper inside the Coming Up section. Putting the layout there, and not on the <section>, keeps the <h2> above the cards instead of making it one more item. Near the top of events/layout.css, the flex rule you switched off while pinning the badge is still a comment. Replace that whole comment with this rule:

Language: CSS
.event-list {
  display: grid;
}

Save, and the page looks the same. display: grid makes .event-list a grid container and each card a grid item. You haven’t said how many columns the grid has, so it has one, and every card gets a row of its own.

Describe the columns next, with a second declaration:

Language: CSS
.event-list {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

grid-template-columns lists the grid’s columns, one size per column, so three sizes make three columns. Each column, and each row, is a track.

The fr unit is a fraction of the free space. The browser takes the container’s width, subtracts any fixed-size tracks and gaps, and shares out the rest in proportion to the fr numbers. It works like the shares you gave flex-grow, but you set it once on the container for a whole column instead of on each item.

Save, and the cards fill three columns:

The Coming Up cards in three columns of equal width that touch each other, two full rows of three and a seventh card alone in a third row.
Seven Cards in Three Equal Columns

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.