DEV Community

Besttech Digital Solutions
Besttech Digital Solutions

Posted on

Flexbox or Grid? A simple rule for choosing

"Should I use Flexbox or Grid?" is one of the most common CSS questions. Here is the rule I use.

Flexbox is for one direction. Grid is for two.

Use Flexbox for a row or column of items

Navigation bars, button groups, centering one thing:

.nav {
  display: flex;
  gap: 1rem;
  align-items: center;
  justify-content: space-between;
}
Enter fullscreen mode Exit fullscreen mode

The items decide how much space they take, and the container lines them up.

Use Grid for rows and columns together

Card layouts, page layouts, galleries:

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 1.5rem;
}
Enter fullscreen mode Exit fullscreen mode

This one rule gives you a responsive layout with no media queries. The number of columns changes as the screen gets narrower.

Combine them

A common pattern is Grid for the page and Flexbox inside each piece:

.card {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
Enter fullscreen mode Exit fullscreen mode

That keeps the buttons at the bottom of every card, even when the text lengths differ.

Quick check

  • Laying things out along one line? Flexbox.
  • Need to control rows and columns? Grid.
  • Not sure? Start with Grid, and use Flexbox for the small parts.

Which one do you reach for first? Tell me in the comments.

Top comments (0)