CSS Flexbox vs Grid: Master Modern Layouts

The Layout Revolution

Before Flexbox and Grid, CSS layouts were painful hacks with floats and positioning. Today, we have two powerful systems that make complex layouts simple.

Flexbox: One-Dimensional Power

Flexbox arranges items along a single axis (row or column). Perfect for components.

/* Centering anything - the classic problem solved */
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

/* Navigation bar */
.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 2rem;
}

/* Card row with equal spacing */
.cards {
    display: flex;
    gap: 1.5rem;
    flex-wrap: wrap;
}
.card {
    flex: 1;
    min-width: 250px;
}

Grid: Two-Dimensional Control

Grid manages rows AND columns simultaneously. Perfect for page layouts.

/* Classic page layout */
.page {
    display: grid;
    grid-template-areas:
        "header header"
        "sidebar main"
        "footer footer";
    grid-template-columns: 250px 1fr;
    grid-template-rows: auto 1fr auto;
    min-height: 100vh;
}

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

/* Responsive image gallery */
.gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 1rem;
}

When to Use Each

Use Case Flexbox Grid
Navigation bar Yes No
Page layout No Yes
Card row Yes Both work
Image gallery No Yes
Centering Yes Both work

Combine Both

The real power comes from combining them: Grid for page structure, Flexbox for component internals. That’s how modern frameworks like Bootstrap and Tailwind CSS work under the hood.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top