7 min read
🎨intermediate

CSS Flexbox — Layouts Made Easy

Master Flexbox to create responsive layouts — centering, spacing, and aligning elements without hacks.

Why Flexbox?

Before Flexbox, centering things in CSS was a nightmare. Developers used floats, tables, and all kinds of hacks. Flexbox solved this — it's a layout system designed to distribute space and align items in a container. If you learn one CSS layout tool, make it Flexbox.

The Basics

css
/* Make a container a flex container */
.container {
  display: flex;
}

/* Items inside automatically sit side by side */

/* Center everything horizontally and vertically */
.container {
  display: flex;
  justify-content: center;  /* horizontal */
  align-items: center;      /* vertical */
  height: 100vh;            /* full screen height */
}

Key Flexbox Properties

On the container (parent): • display: flex — activates flexbox • flex-direction: row | column — horizontal or vertical • justify-content — align along main axis (space-between, center, flex-start, flex-end, space-around) • align-items — align along cross axis (center, stretch, flex-start, flex-end) • gap: 16px — space between items • flex-wrap: wrap — items wrap to next line On the items (children): • flex: 1 — item grows to fill available space • flex-shrink: 0 — item won't shrink • align-self — override alignment for one item

Common Layouts

css
/* Navbar: logo left, links right */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
}

/* Card grid that wraps */
.card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.card {
  flex: 1 1 300px; /* grow, shrink, min-width */
}

/* Perfect center */
.centered {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
Pro Tip

When something won't center, the fix is almost always: put display: flex; justify-content: center; align-items: center; on the PARENT element. Not the child.

Try It Yourself

Build a navigation bar with a logo on the left and 3 links on the right using Flexbox. Then create a 3-column card layout below it that wraps to 1 column on small screens (hint: use flex-wrap and a min-width on cards).

Ready to build?

Put what you learned into practice — pick a project and start coding.

Start Building Free