CSS Grid vs Flexbox

CSS Grid vs Flexbox: When to Use Each Layout System with Practical Examples for Modern Responsive Design

Understand the key differences between CSS Grid and Flexbox. Learn when to use each with real-world examples including navigation bars, card layouts, and full-page responsive designs.

CSS Grid and Flexbox are powerful layout tools, but beginners often struggle to choose between them. The simple rule: Flexbox is for one-dimensional layouts (rows OR columns), Grid is for two-dimensional layouts (rows AND columns). Let's explore with examples.

When to Use Flexbox

Flexbox excels at distributing items along a single axis. Perfect for navigation bars, centering elements, or aligning items in a row.

Example: Navigation Bar

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.nav-links {
  display: flex;
  gap: 2rem;
}

Example: Card Footer with Flexbox

.card {
  display: flex;
  flex-direction: column;
  height: 300px;
}

.card-footer {
  margin-top: auto; /* Pushes footer to bottom */
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

When to Use CSS Grid

Grid is ideal for complex layouts with rows and columns, like image galleries, dashboards, or magazine-style layouts.

Example: Responsive Card Grid

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

Example: Holy Grail Layout

.layout {
  display: grid;
  grid-template-areas: 
    "header header"
    "sidebar main"
    "footer footer";
  grid-template-columns: 200px 1fr;
  gap: 20px;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

Using Them Together

Modern layouts often combine both: Grid for the overall page structure, Flexbox for components inside each grid cell.

.page {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 20px;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.main-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

Remember: Flexbox is for components, Grid is for layouts. Master both and you can build anything!

Comments

Popular posts from this blog

How to Center a Div - The 3 Modern Ways (2026)

Call by Value vs Call by Reference in C Programming (With Simple Examples)

Build a Simple Calculator with HTML, CSS & JavaScript