Modern CSS

Flexbox and Grid

Use Flexbox for one-dimensional alignment and Grid for two-dimensional layout in real interfaces.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Use Flexbox for one-dimensional alignment and Grid for two-dimensional layout in real interfaces. This hands-on tutorial focuses on practical implementation of flexbox and grid concepts.

Flexbox and Grid

Modern layout starts with one key question: are you arranging items in one dimension or two?

Use Flexbox When

  • you need a row or column
  • you want easy centering
  • items should grow or shrink along one axis
.nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}

Use Grid When

  • you need rows and columns together
  • cards should line up cleanly
  • layout areas matter more than item order
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 1.25rem;
}

Flexbox Essentials

  • justify-content controls the main axis
  • align-items controls the cross axis
  • flex-wrap allows wrapping when space is tight
  • gap creates consistent spacing without margin hacks

Grid Essentials

  • grid-template-columns defines column structure
  • repeat() keeps code short
  • minmax() makes layouts responsive
  • gap works here too

A Useful Pattern

.page {
  display: grid;
  grid-template-columns: 18rem 1fr;
  min-height: 100vh;
}

@media (max-width: 900px) {
  .page {
    grid-template-columns: 1fr;
  }
}

This pattern works well for docs layouts, dashboards, and course pages.

Next Step

Continue to Responsive Units and Media Queries to make layouts adapt smoothly across screens.