CohortX
Блог

Flexbox and Grid: which to use when

2 августа 2026 г. · 2 мин чтения · Читать по-русски · Антон Молотило

The rule in one line

Flexbox is for one direction. A row or a column.

Grid is for two directions at once. A grid of rows and columns.

That rule covers ninety per cent of cases. Details and caveats follow.

Flexbox: when

Anything that lines up:

  • a navigation bar;
  • a row of buttons;
  • a card with an image on the left and text on the right;
  • an element pushed to one edge;
  • centring a single thing.

The core idea: there's a main axis and a cross axis. You control how items distribute along the main one and how they align across it.

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

Three lines solve what once required floats and tricks.

Grid: when

Anything arranged in a grid:

  • a gallery of cards;
  • the overall page layout: header, sidebar, content, footer;
  • table-like blocks;
  • complex forms aligned by column.

The core idea: you describe the grid, then place items into its cells.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
}

That declaration produces a responsive gallery without a single breakpoint: there will be as many columns as fit, none narrower than the stated width.

Choosing in a borderline case

Ask yourself: do I need to control rows and columns simultaneously?

Yes — grid. No — flexbox.

Second question: who's in charge, the container or the content? If you define the structure in advance and place things into it, grid. If items distribute themselves across available space, flexbox.

They can and should be combined

Standard practice: the overall page layout on a grid, with flexbox inside each block for its contents.

That isn't a compromise but the normal approach: the mechanisms complement each other.

Common mistakes

Spacing with margins instead of gaps. The gap property works in both mechanisms and spares you fiddling with margins on edge items.

Fixed heights. The layout breaks as soon as there's more text. Set a minimum height, not an exact one.

Grid where a single line would do. Complexity with no benefit.

Forgetting shrink behaviour. Flex items may by default shrink below their content, clipping text. Fixed by setting a minimum size.

Too many nested containers. Five layout levels inside each other signals a structure invented as you went.

What to learn first

Flexbox: it's needed more often and easier to grasp. Grid straight afterwards, because without it page-level layout comes out clumsy.

Both take about a week of practice, provided you build something real rather than reading about properties.

Хватит читать — пора делать

На CohortX можно найти команду под пет-проект и получить тот самый опыт, о котором спрашивают на собеседовании.

Похожие статьи