How does Flexbox work in CSS?

Flexbox is a 1D layout model - set display:flex on a container to control how its children are arranged along a main axis and a cross axis.

CSSFlexboxLayout

Overview

Flexbox (Flexible Box Layout) arranges child elements along a single axis (row or column). The parent becomes a **flex container** and the children become **flex items**. Two axes control everything: the main axis (direction of layout) and the cross axis (perpendicular to it).

Key Points

  • •`display: flex` on the parent turns it into a flex container.
  • •`flex-direction: row` (default) or `column` sets the main axis.
  • •`justify-content` aligns items along the **main** axis.
  • •`align-items` aligns items along the **cross** axis.
  • •`flex-wrap: wrap` lets items flow onto multiple lines instead of overflowing.
  • •`gap` adds spacing between items without affecting outer edges.

Examples

Basic flex row with centered items

css
.nav {
  display: flex;
  flex-direction: row;      /* default: left to right */
  justify-content: space-between; /* spread items along main axis */
  align-items: center;      /* center on cross axis */
  gap: 1rem;                /* space between items */
}

justify-content options

css
/* flex-start   | items packed to start (default)     */
/* flex-end     | items packed to end                   */
/* center       | items centered                        */
/* space-between| equal gaps between items              */
/* space-around | equal space around each item          */
/* space-evenly | equal space between items and edges   */
.container { justify-content: space-between; }

Flex items growing to fill space

css
.sidebar { flex: 0 0 240px; }   /* fixed 240px, no grow/shrink */
.main    { flex: 1; }            /* takes all remaining space */

/* flex is shorthand for: flex-grow flex-shrink flex-basis */

Responsive card row that wraps

css
.card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
}
.card {
  flex: 1 1 280px; /* grow, shrink, minimum 280px */
}

Cards fill available space but wrap when they would be smaller than 280px.

Override alignment for a single item

css
.container { display: flex; align-items: center; }
.special   { align-self: flex-end; } /* overrides just this one item */

Pro Tip

A mental model: `justify-content` controls the main axis (the direction of flex-direction), `align-items` controls the perpendicular axis. When `flex-direction: column`, those axes swap - so `justify-content` becomes vertical.