Flexbox

The CSS layout mode for arranging items in a row or a column, with full control over spacing and alignment.

CSS6 min readConcept 1 of 9

What it is

Flexbox is a layout mode in CSS for placing items in a single direction, either a row or a column. You turn it on with display: flex on a container, and its direct children become flexible items that share the space along one line.

Before flexbox, lining boxes up and centering them meant floats, inline-block quirks, and margin hacks. Flexbox replaces all of that with a small set of properties that say what you actually mean: pack these to the center, push them to the edges, let this one grow.

Why it matters

You reach for flexbox constantly on real work: navigation bars, button toolbars, a row of cards, a label next to an icon, centering a thing both ways. It is the everyday tool for one-dimensional layout.

Knowing flexbox well is the difference between fighting CSS and directing it. Most layout bugs juniors hit are really a misunderstanding of which axis a property acts on.

How it works

Setting display: flex on a container creates a flex context. Inside it there are two axes: the main axis (the direction items flow) and the cross axis (perpendicular to it). flex-direction decides which is which: row (default) runs the main axis left to right, column runs it top to bottom.

justify-content positions items along the main axis. Common values are flex-start, center, space-between, and space-around. align-items positions them along the cross axis, so align-items: center vertically centers a row of items.

gap adds consistent space between items without margin hacks. For sizing, flex-grow lets an item expand to fill spare space, flex-shrink lets it give space back, and flex-basis sets its starting size. The shorthand flex: 1 is the one you will type most, meaning grow to share space equally.

Try it

Change a property and watch the boxes move to match. Notice how flipping the direction to column changes what justify-content does.

.container {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
1
2
3
4

Items in a row, packed to the start.

justify-content
flex-direction

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1In a row, which property moves items left and right along the main axis?
  2. 2You set flex-direction: column. What does justify-content now control?
  3. 3What is the cleanest way to add even space between flex items?

Remember this

  • display: flex turns a container into a one-dimensional layout, row or column.
  • flex-direction sets the main axis; row is the default.
  • justify-content aligns along the main axis; align-items aligns along the cross axis.
  • gap spaces items cleanly; flex: 1 makes an item grow to share space.

Done with this concept?

Mark it complete to track your progress. No login needed.