Overview

Flexbox is the layout model for arranging items in a single row or column. It handles alignment, spacing, and distribution without floats or hacks. This tutorial covers the container and item properties, with practical layout examples.

Enabling Flexbox

.container {
  display: flex;
}

All direct children become flex items and are laid out along the main axis.

Container Properties

flex-direction

ValueMain axis
row (default)Left to right
row-reverseRight to left
columnTop to bottom
column-reverseBottom to top

justify-content (main axis)

ValueEffect
flex-startPacked at the start
centerCentered
flex-endPacked at the end
space-betweenEqual space between items
space-aroundEqual space around each item
space-evenlyEqual space between and at the edges

align-items (cross axis)

ValueEffect
stretch (default)Items fill the container height
flex-startAligned to the top
centerVertically centered
flex-endAligned to the bottom
baselineAligned by text baseline

flex-wrap

.container {
  flex-wrap: wrap;
}

By default items shrink to fit on one line. wrap allows them to move to the next line.

Item Properties

flex-grow, flex-shrink, flex-basis

.item {
  flex: 1 1 200px; /* grow shrink basis */
}
PropertyMeaning
flex-growHow much extra space the item takes
flex-shrinkHow much the item shrinks when space is tight
flex-basisInitial size before growing or shrinking

align-self

.item {
  align-self: flex-end;
}

Overrides the container's align-items for a single item.

order

.item-featured {
  order: -1;
}

Lower values appear first. Useful for moving a featured item to the front without changing the HTML.

Practical Layouts

Perfect Centering

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

Sticky Footer

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

main {
  flex: 1;
}

Navigation Bar

.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

Card Grid with Wrapping

.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.card {
  flex: 1 1 300px;
}

Flexbox vs Grid

DimensionFlexboxGrid
Layout directionOne-dimensionalTwo-dimensional
Best forRows or columns of itemsFull page layouts
SizingContent-drivenTrack-driven