cssflexboxlayoutweb design

CSS Flexbox Complete Guide with Examples

Master CSS Flexbox with this comprehensive guide covering all properties with visual examples.

March 15, 2024ยท10 min read

What is Flexbox?

Flexbox (Flexible Box Layout) is a CSS layout model that arranges elements in rows or columns with powerful alignment and distribution controls.

Container Properties

.container {
  display: flex;
  flex-direction: row; /* row | row-reverse | column | column-reverse */
  flex-wrap: nowrap; /* nowrap | wrap | wrap-reverse */
  justify-content: flex-start; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
  align-items: stretch; /* flex-start | flex-end | center | stretch | baseline */
  gap: 16px;
}

Item Properties

.item {
  flex-grow: 0; /* How much to grow relative to siblings */
  flex-shrink: 1; /* How much to shrink if needed */
  flex-basis: auto; /* Initial size before growing/shrinking */
  /* Shorthand: flex: grow shrink basis */
  flex: 1; /* flex: 1 1 0% */
  align-self: auto; /* Override container align-items */
}

Common Patterns

Centering

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

Holy Grail Layout

.layout {
  display: flex;
}
.main { flex: 1; }
.sidebar { width: 250px; }

Try our Flexbox Playground to visualize these properties.