Sobes.tech
Junior

Is it possible to use CSS Grid and Flexbox together?

sobes.tech AI

Answer from AI

Yes, CSS Grid and Flexbox can be used together, and it is often even recommended for creating complex and responsive layouts.

  • CSS Grid is great for building the overall structure of the page — for example, placing main areas (header, sidebar, content, footer).
  • Flexbox is better used for aligning and distributing elements within these areas — for example, for menus, buttons, cards.

Example:

.container {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: 60px 1fr 40px;
  height: 100vh;
}
.sidebar {
  grid-column: 1;
  grid-row: 1 / 4;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.content {
  grid-column: 2;
  grid-row: 2;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

Thus, Grid sets the main grid, and Flexbox manages the layout of elements inside the cells.