Sub topic 10
Arrange project cards with CSS Grid
This chapter assumes you can write an HTML page with semantic sections, link a stylesheet, and apply the box model (padding, margin, box-sizing). It also assumes you have used Flexbox for the navigation. Here you will build the project cards in the #projects section and arrange them with CSS Grid.
Why Grid for the project cards
Flexbox lays out items along one axis. It works well for a row of navigation links. A set of project cards is a different problem. You want rows and columns that line up, and you want the number of columns to change with the screen width.
CSS Grid is a layout system that controls rows and columns at the same time. You turn an element into a grid container, and its direct children become grid items. The browser places the items into cells.
| Question | Flexbox | Grid |
|---|---|---|
| Main direction | One axis at a time | Rows and columns together |
| Who sets sizes | Content tends to drive sizes | The container's track definitions drive sizes |
| Good fit | Navigation, toolbars, centering | Card galleries, page regions |
The two are not rivals. A card can be a grid item and also use Flexbox inside itself.
Write the card markup
Each project is an article element, because a card is a self-contained piece of content. Put the cards inside a wrapper with the class project-list. The wrapper is the grid container.
<section id="projects">
<h2>Projects</h2>
<div class="project-list">
<article class="project-card">
<h3>Recipe Finder</h3>
<p>A small search page for weeknight recipes.</p>
<a href="https://example.com/recipes">View project</a>
</article>
<article class="project-card">
<h3>Trail Map</h3>
<p>An interactive map of local walking routes.</p>
<a href="https://example.com/trails">View project</a>
</article>
<article class="project-card">
<h3>Budget Notes</h3>
<p>A simple tracker for monthly spending.</p>
<a href="https://example.com/budget">View project</a>
</article>
</div>
</section>The headings follow the page outline. The page title is an h1, the section is an h2, and each card title is an h3. Do not pick heading levels for their size. Set size in CSS.
Create the grid container
Two declarations are enough to start: display: grid and gap.
#projects .project-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
gap: 1.5rem;
}Take the rules one at a time.
display: gridmakes.project-lista grid container.gapsets the space between rows and columns. It adds no space at the outer edges, so you don't need to remove a margin from the last item.grid-template-columnsdefines the column tracks. A track is one row or one column of the grid.
Read the column definition
The line repeat(auto-fit, minmax(16rem, 1fr)) has three parts.
minmax(16rem, 1fr)gives each column a minimum width of16remand a maximum of1fr. Anfrunit is a fraction of the free space in the container. A column of1frtakes an equal share of what is left.repeat(...)repeats that column definition.auto-fittells the browser to repeat as many times as fit, then let the columns share the leftover space.
Suppose the container is 60rem wide with a 1.5rem gap. Two columns need 32rem plus one gap, and that fits. Three columns need 48rem plus two gaps (3rem), a total of 51rem, and that fits too. Four columns need 64rem plus three gaps, which is too wide. The browser creates three columns and stretches each to share the rest. On a phone with a 20rem container, only one column fits, so the cards stack.
This is why the layout needs no breakpoints to switch between one, two and three columns.
auto-fit versus auto-fill
auto-fill looks similar, and the difference shows only when there are fewer items than columns that could fit.
auto-fillkeeps empty tracks. With two cards in a wide container, you get two cards at their minimum size and empty space on the right.auto-fitcollapses empty tracks to zero width, so the two cards stretch to fill the row.
For a card list you usually want auto-fit. If you prefer cards to keep a consistent maximum width even when there are few, use auto-fill.
Set up the cards themselves
The cards are grid items, and by default each stretches to the height of its row. That keeps cards in one row equal in height. Style them with the box model from earlier chapters.
.project-card {
padding: var(--space);
border: 1px solid #d5dbe1;
border-radius: 0.5rem;
background: var(--color-bg);
}
.project-card h3 {
margin-top: 0;
}This uses the --space and --color-bg custom properties defined in :root. If you change the property, every card follows.
Because box-sizing: border-box is set globally, the padding and border do not make a card wider than its grid track.
Keep the link at the bottom of each card
When card text has different lengths, the links sit at different heights. Make each card a vertical Flexbox container and push the link down.
.project-card {
display: flex;
flex-direction: column;
}
.project-card a {
margin-top: auto;
}An auto margin absorbs all free space in a Flexbox container. The link moves to the bottom edge and the cards look aligned. This is a normal example of combining the two systems: Grid for the page-level arrangement, Flexbox for the inside of one card.
Control placement when you need to
Auto-placement fills the grid in source order. Sometimes one card should be larger. You can ask an item to span more than one column.
.project-card.featured {
grid-column: span 2;
}span 2 means the item takes two column tracks. Be careful here. If only one column fits, such as on a phone, a two-column span forces the browser to create an extra implicit column, and the layout overflows. Wrap the rule in a media query so it applies only when there is room:
@media (min-width: 48rem) {
.project-card.featured {
grid-column: span 2;
}
}The 48rem breakpoint matches the one used for page padding in the responsive chapter.
Common errors
- Styling the wrong element.
display: gridmust be on the parent. Setting it on a card does nothing for the card's siblings. - A wrapper in between. Only direct children are grid items. If you wrap each card in an extra
div, thedivis the item and your card style may not stretch. - Fixed widths on cards. A
width: 300pxon a card fights the track size. Let the track control width. - Overflow on narrow screens. If the minimum in
minmax()is larger than the container, the column overflows. For very narrow screens, useminmax(min(16rem, 100%), 1fr). Themin()function picks the smaller of the two values, so the column never exceeds the container. - Confusing
gapwith margins. Margins on cards add to the gap. Use one or the other. - Using Grid for reading order changes. Grid can visually reorder items, but screen readers and the Tab key follow source order. Keep the HTML in a logical order.
Inspect the grid in your browser
Browser developer tools can draw the grid. In Chrome, Edge and Firefox, open the Elements or Inspector panel and select .project-list. Click the small grid badge next to it. The browser overlays the track lines and gaps. Resize the window and watch the number of columns change. This is the fastest way to find out why an item is not where you expect.
Final stylesheet for this section
#projects .project-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(16rem, 100%), 1fr));
gap: 1.5rem;
}
.project-card {
display: flex;
flex-direction: column;
padding: var(--space);
border: 1px solid #d5dbe1;
border-radius: 0.5rem;
background: var(--color-bg);
}
.project-card h3 {
margin-top: 0;
}
.project-card a {
margin-top: auto;
}Exercise
A container is 40rem wide. Its grid uses repeat(auto-fit, minmax(12rem, 1fr)) with gap: 1rem. How many columns does the browser create, and how wide is each column?
Show answer
Three columns fit: three minimum widths plus two gaps is 36rem + 2rem = 38rem, which is within 40rem. Four columns need 48rem + 3rem = 51rem, which is too wide. The free space after the gaps is 40rem - 2rem = 38rem, and each column gets one third of it, about 12.67rem.
Exercise
You have two project cards in a wide container, but they sit at their minimum width with empty space on the right. Which change fixes this, and why?
Show answer
Replace auto-fill with auto-fit. With auto-fill, empty tracks are kept, so the two cards stay at their minimum size. With auto-fit, empty tracks collapse to zero and the 1fr maximum lets the two cards stretch across the row.