Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

CSS Grid vs Flexbox: Differences, Examples and When to Use Each

CSS Grid and Flexbox can produce similar interfaces but resolve the size and position of items differently. The distinction becomes important when labels vary in length, a final card row is incomplete, URLs are long or a component is placed in a narrow container. This guide uses concrete layouts to explain which behavior to choose and why.

Published Written by Reading time 12 min read
On this page Contents: quick navigation between sections

The fundamental difference: one dimension versus two

FeatureFlexboxCSS Grid
DimensionsOne axis per lineRows and columns
WrappingIndependent linesShared tracks
Typical useToolbars and actionsCard collections and panels
Space distributionflex-grow, flex-shrink, flex-basisfr, minmax(), tracks

Flexbox resolves item sizes along the main axis defined by flex-direction. Wrapping creates additional lines without establishing shared columns between them. Grid establishes tracks on both axes, letting items in separate rows share column boundaries. Neither model is restricted to a particular component size. [1][2][3]

Choose Grid when several rows must align. Start with Flexbox when button widths should follow labels and spare space should be distributed along one axis.

Flexbox in practice: a toolbar

<div class="toolbar">
  <button type="button">Filter</button>
  <button type="button">Sort</button>
  <button class="export" type="button">Export</button>
</div>
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.75rem;
}

.export {
  margin-inline-start: auto;
}

The buttons retain content-driven widths. flex-wrap: wrap lets them move onto another line, while an automatic inline-start margin pushes Export towards the end of its current line if free space remains. [1][4][12]

The initial flex: 0 1 auto allows shrinking but not growing. flex: 1 1 12rem sets a 12 rem basis and enables growing and shrinking, subject to minimum sizing. Shrink factors are scaled by the flex base size, so equal flex-shrink values do not necessarily remove equal pixel widths.

Grid in practice: a dashboard

<div class="dashboard">
  <header>Overview</header>
  <aside>Filters</aside>
  <main>Results</main>
</div>
.dashboard {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  grid-template-areas:
    "header"
    "filters"
    "main";
  gap: 1rem;
}

.dashboard > header {
  grid-area: header;
}

.dashboard > aside {
  grid-area: filters;
}

.dashboard > main {
  grid-area: main;
  min-inline-size: 0;
}

@media (min-width: 48rem) {
  .dashboard {
    grid-template-columns: 14rem minmax(0, 1fr);
    grid-template-areas:
      "header header"
      "filters main";
  }
}

grid-template-areas names regions, and grid-template-columns defines track sizes. In the example, sections stack on narrow screens; at 48 rem the filter track becomes 14 rem wide and the main content takes the remainder. The breakpoint is illustrative, not universal. [2][6]

An fr unit is a share of available space, not a percentage of container width. With 1fr 2fr, after gaps and applicable sizing constraints, the second track receives twice the flexible share. minmax(0, 1fr) permits a track to shrink below its automatic minimum.

Five cards across two rows

<div class="flex-list">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
</div>

<div class="grid-list">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
</div>
.flex-list,
.grid-list {
  inline-size: 100%;
  max-inline-size: 640px;
  gap: 16px;
}

.flex-list {
  display: flex;
  flex-wrap: wrap;
}

.flex-list > div {
  flex: 1 1 180px;
  min-inline-size: 0;
}

.grid-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr));
}

.flex-list > div,
.grid-list > div {
  box-sizing: border-box;
  padding: 1rem;
  border: 1px solid currentColor;
}

Compare containers with 640 px of inner width, a 16 px gap and a 180 px basis. Five simple cards produce three items on the first row and two on the second. Flexbox with flex-grow: 1 distributes free space separately: first-row cards are about 202.67 px wide, while second-row cards are 312 px each. [3][5]

Grid retains three tracks of about 202.67 px in both rows, leaving the final cell empty. Use Flexbox if the last row should expand, or Grid if edges must align. These figures assume no extra margins or content constraints.

Responsive Grid: auto-fit, auto-fill and minmax

.cards {
  display: grid;
  gap: 1rem;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
}

/* Alternative: preserve space for empty columns. */
.cards--reserved {
  grid-template-columns: repeat(auto-fill, minmax(min(100%, 16rem), 1fr));
}

repeat(auto-fit, minmax(min(100%, 16rem), 1fr)) adjusts the number of columns to available space. The inner min() prevents a 16 rem minimum from itself exceeding a narrower container, but cannot prevent every form of content overflow. [2][6]

With two cards and room for four tracks, auto-fill retains the empty tracks; auto-fit collapses them so occupied tracks can expand. A track occupied in any row is not empty, so auto-fit will not automatically stretch the last two cards if a preceding row uses all columns.

Alignment and spacing: align, justify and gap

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-block-size: 12rem;
}

.grid-center {
  display: grid;
  place-items: center;
  min-block-size: 12rem;
}

In Flexbox, justify-content follows the main axis and align-items the cross axis. flex-direction: column changes their orientation. In Grid, justify-items aligns items in the inline direction and align-items in the block direction. justify-content and align-content distribute the track collection when spare space exists. [7][12]

Use place-items: center for a single Grid cell. Use both alignment properties in Flexbox because justify-items is ignored there. gap separates items or tracks without adding outer margins.

Combining both models: product cards

<div class="products">
  <article class="product">
    <h2>Starter</h2>
    <p>Basic features</p>
    <a href="/en/starter">Details</a>
  </article>

  <article class="product">
    <h2>Professional</h2>
    <p>More features and priority support</p>
    <a href="/en/professional">Details</a>
  </article>
</div>
.products {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
  gap: 1rem;
  align-items: stretch;
}

.product {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.product > a {
  margin-block-start: auto;
  align-self: start;
}

Grid establishes shared columns and each card uses vertical Flexbox. An automatic margin above its link absorbs spare space, placing actions at the bottom of cards in the same row despite different description lengths. [3][12]

Different rows need not have equal heights. If titles or prices must also align with corresponding rows of neighboring cards, independent nested layouts are insufficient; consider subgrid.

Why an item refuses to shrink

.search-row {
  display: flex;
  gap: 1rem;
}

.search-result {
  flex: 1 1 auto;
  min-inline-size: 0;
  overflow-wrap: anywhere;
}

.content-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
  gap: 1rem;
}

.content-grid > * {
  min-inline-size: 0;
  overflow-wrap: anywhere;
}

.content-grid img {
  max-inline-size: 100%;
  block-size: auto;
}

Flex and grid items can have an automatic minimum related to their content. Long URLs, images and code can push tracks outside the container. In a horizontal layout, min-inline-size: 0 allows an item to shrink, while minmax(0, 1fr) removes the automatic minimum of a flexible track. [1][6][8]

Do not hide content by default. Use overflow-wrap: anywhere for unbroken text, constrain image sizes, and consider overflow: auto for code containers. A height-constrained column flex layout may similarly need min-block-size: 0 on a scrolling child.

Accessibility: visual order versus DOM order

order, row-reverse, explicit Grid placement and grid-auto-flow: dense can change visual order without equivalent changes to logical reading or keyboard navigation. Focus may appear to jump unpredictably. [1][2][9]

Keep semantic HTML in meaningful order. The dashboard header, filters and results should remain understandable without CSS. Test with Tab, zoom and long translations instead of repairing order with positive tabindex values.

Responsive components rather than viewport widths

.panel {
  container-type: inline-size;
}

.panel-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

@container (min-width: 30rem) {
  .panel-content {
    display: grid;
    grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
  }
}

A component in a narrow sidebar can require a vertical layout even on a large monitor. Set container-type: inline-size on an ancestor, then use @container to change a descendant layout when the container reaches the intended size. [11]

The example starts with column Flexbox. When the panel is at least 30 rem wide in the standard horizontal writing mode, the child switches to two-column Grid. Without query support the base layout remains usable.

Subgrid: shared tracks inside cards

.catalog {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 1rem;
}

.catalog-card {
  display: grid;
  grid-row: span 3;
  grid-template-rows: auto 1fr auto;
}

@supports (grid-template-rows: subgrid) {
  .catalog-card {
    grid-template-rows: subgrid;
  }
}

A regular nested grid resolves its own tracks. grid-template-rows: subgrid lets a card participate in the parent row tracks. Each sample card spans three rows and assumes three direct children: title, description and action. [2][10]

Titles and actions can then share track boundaries with cards in the same group. The @supports rule leaves independent rows as a fallback where subgrid is unavailable.

Performance and maintainability

Compare CSS Grid and Flexbox at different widths in the POLPROG Responsive Tester.

There is no universal Grid-versus-Flexbox performance winner. Layout cost depends on item count, content complexity, size constraints and how frequently geometry changes. If layout is expensive, record an actual interaction in the browser Performance panel rather than relying on one synthetic benchmark.

Choose the simpler model for the desired behavior. If Flexbox requires manually calculated columns and filler elements, Grid may simplify the code. If Grid requires many rules for a small toolbar, Flexbox may be clearer.

Flexbox suits items that distribute space along a single axis. Grid suits items that need shared row or column boundaries. Combining them often gives the clearest code: Grid defines the collection, and Flexbox arranges the contents of each item. Choose the behavior that survives changes in content and available width, rather than assuming one layout algorithm is always faster.

Tools for this topic

CSS CSS Grid Flexbox CSS Layout Responsive Web Design Subgrid Container Queries Web Accessibility

Frequently asked questions

Does Grid replace Flexbox?

No. Both solve different problems and can coexist within a component. [3]

Can Flexbox create multiple rows?

Yes, with flex-wrap: wrap, but each line distributes its free space independently. [5]

When should I use auto-fit rather than auto-fill?

When occupied tracks should expand into space left by empty tracks. auto-fill retains those tracks. [2]

Why can 1fr cause overflow?

A track's automatic minimum may depend on content. minmax(0, 1fr) permits shrinking the track, but overflowing content still needs handling. [6][8]

Is Grid faster than Flexbox?

Not universally. Measure layout cost in the real interaction.

Sources and references

  1. W3C, CSS Flexible Box Layout Module Level 1↩1↩2↩3↩4
  2. W3C, CSS Grid Layout Module Level 2↩1↩2↩3↩4↩5↩6
  3. MDN, Relationship of grid layout to other layout methods↩1↩2↩3↩4
  4. MDN, Controlling ratios of flex items along the main axis↩
  5. MDN, Mastering wrapping of flex items↩1↩2
  6. MDN, grid-template-columns↩1↩2↩3↩4
  7. MDN, Box alignment in grid layout↩
  8. MDN, min-width↩1↩2
  9. MDN, Grid layout and accessibility↩
  10. MDN, Subgrid↩
  11. MDN, container-type↩
  12. MDN, Aligning items in a flex container↩1↩2↩3

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning