Skip to main content
Practice Problems

CSS flexbox layout

What is Flexbox?

Flexbox (Flexible Box Layout) is a CSS layout model designed for one-dimensional layouts — arranging items in a row or a column with flexible sizing and alignment.


Enabling Flexbox

css
.container { display: flex; /* or inline-flex */ }

All direct children of a flex container become flex items.

Main Axis and Cross Axis

Flexbox works along two axes:

  • Main axis — defined by flex-direction (default: horizontal, left to right)
  • Cross axis — perpendicular to the main axis
css
.container { display: flex; flex-direction: row; /* Main axis: horizontal (default) */ /* flex-direction: column; Main axis: vertical */ }

Container Properties

PropertyDescription
flex-directionDirection of items: row, row-reverse, column, column-reverse
flex-wrapWhether items wrap: nowrap, wrap, wrap-reverse
justify-contentAlignment along main axis: flex-start, center, space-between, space-around, space-evenly
align-itemsAlignment along cross axis: stretch, flex-start, center, flex-end, baseline
align-contentAlignment of wrapped lines: same values as justify-content
gapSpacing between flex items

Example: Centering Content

css
.container { display: flex; justify-content: center; align-items: center; height: 100vh; }

Item Properties

PropertyDescription
flex-growHow much an item should grow relative to others (default: 0)
flex-shrinkHow much an item should shrink relative to others (default: 1)
flex-basisInitial size before growing/shrinking (default: auto)
flexShorthand for flex-grow flex-shrink flex-basis
align-selfOverride align-items for a single item
orderChange visual order without changing HTML

Example: Flexible Items

css
.sidebar { flex: 0 0 250px; } /* Fixed 250px, no grow, no shrink */ .main { flex: 1; } /* Takes all remaining space */ .aside { flex: 0 0 200px; } /* Fixed 200px */

Common Flexbox Patterns

css
.navbar { display: flex; justify-content: space-between; align-items: center; padding: 0 20px; }

Equal-height Cards

css
.cards { display: flex; gap: 16px; flex-wrap: wrap; } .card { flex: 1 1 300px; /* Grow, shrink, min 300px */ }
css
body { display: flex; flex-direction: column; min-height: 100vh; } main { flex: 1; }

Important:

Flexbox is best for one-dimensional layouts (a single row or column). For two-dimensional layouts (rows AND columns simultaneously), use CSS Grid. In practice, flex and grid are often combined.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems