Lesson 5 / 7

Flexbox and Grid Layout

Flexbox — one dimension at a time

.nav-links {n    display: flex;n    gap: 24px;n    align-items: center;n    justify-content: space-between;n}

Flexbox arranges items in a single row or column and distributes space between them — it is the right tool for a navigation bar, a row of buttons, or centering one thing inside another, which used to require awkward workarounds before Flexbox existed. justify-content controls spacing along the main direction; align-items controls alignment across the other direction.

Common Flexbox properties

.container {n    display: flex;n    flex-direction: row;      /* or: column */n    flex-wrap: wrap;          /* let items wrap to a new line */n}n.item {n    flex: 1;                  /* grow to fill available space, shared equally */n}

Grid — two dimensions at once

.card-grid {n    display: grid;n    grid-template-columns: repeat(3, 1fr);n    gap: 24px;n}

CSS Grid handles rows and columns together, which makes it the better tool for a genuine grid layout — a gallery, a dashboard, or (as it happens) the course card grid on this very site’s homepage, which uses exactly this pattern.

Responsive columns without media queries

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

This single line creates a grid that automatically fits as many 240px-minimum columns as will comfortably fit the available width, reflowing on its own as the browser resizes — no media query breakpoints required at all for this specific case.

Flexbox vs Grid: which to reach for

Rule of thumb: if you are arranging items in a single row or column, reach for Flexbox. If you are arranging items into an actual grid of rows AND columns, reach for Grid. Many real layouts use both together — Grid for the overall page structure, Flexbox for aligning items within one of those grid areas.