Skip to content
Retr0 Academy
Advanced CSS

Advanced CSS · 2 min read

Grid and Flexbox Layouts

When to use Grid vs Flexbox, named areas, auto-fit with minmax, alignment, and combining both.

Flexbox is one-dimensional: it distributes items along a single axis and lets content decide sizes. Grid is two-dimensional: you define rows and columns first, then place items into them. Real layouts use both: Grid for the page skeleton, Flexbox inside components.

Grid tracks, spans and auto-placement.
Grid tracks, spans and auto-placement.

Named grid areas

grid-template-areas lets you draw the layout in ASCII and rearrange it per breakpoint without touching the HTML:

Dashboard with named areas
<div class="app">
<header>Header</header>
<nav>Nav</nav>
<main>
  <div class="cards">
    <article>Lessons 12</article><article>Quiz 92%</article>
    <article>Diploma</article><article>Streak 5</article>
  </div>
</main>
<aside>Leaderboard</aside>
<footer>Footer</footer>
</div>

Edit this example in the Playground.

Open in Playground

auto-fit + minmax: responsive without media queries

repeat(auto-fit, minmax(140px, 1fr)) means: fit as many columns as possible, each at least 140px, then stretch them equally. Resize the preview and the cards reflow on their own.

KeywordEmpty tracks
auto-fillKept, so items stay at their minimum width
auto-fitCollapsed, so items stretch to fill the row

Flexbox inside components

justify-content distributes free space on the main axis.
justify-content distributes free space on the main axis.
Toolbar: push items apart with margin-left: auto
<div class="bar">
<strong>Retr0</strong>
<a href="#">Learn</a><a href="#">Playground</a>
<button class="push">Connect</button>
</div>
<div class="media">
<div class="avatar"></div>
<p>Flex items shrink and wrap. <code>min-width: 0</code> lets long text truncate instead of overflowing.</p>
</div>

Edit this example in the Playground.

Open in Playground

Decision guide

  • Laying out the page or a 2D gallery? Grid.
  • Aligning items in a row (nav, toolbar, button group)? Flexbox.
  • Need items in different rows to line up in columns? Grid (or subgrid).
  • Centering one thing? Either: display: grid; place-items: center.

Summary

Grid defines tracks and places items in two dimensions; named areas make responsive rearrangement trivial. Flexbox shares space along one axis. Combine them: Grid for structure, Flexbox for components.