Unit 6 ยท Cascading Style Sheets (CSS)

6.6.2Flexbox

Flexbox arranges items in one direction (a row or a column), handling spacing, alignment and wrapping automatically.

.row { display: flex; }123main axis (justify-content)main startmain endcross axis (align-items)Withflex-direction:column, theaxes swap
Flexbox: justify-content works along the main axis, align-items along the cross axis
HTML
<div class='row'>
  <div class='box'>1</div>
  <div class='box'>2</div>
  <div class='box'>3</div>
</div>
CSS
.row {
  display: flex;                 /* turns on flexbox: children become flex items */
  flex-direction: row;           /* row (default), column, row-reverse, column-reverse */
  justify-content: space-between;/* main axis: flex-start, center, flex-end, space-around, space-evenly */
  align-items: center;           /* cross axis: stretch (default), flex-start, center, flex-end */
  flex-wrap: wrap;               /* allow items to move to the next line */
  gap: 16px;                     /* space between items */
}

.box { flex: 1 1 200px; }        /* grow, shrink, basis: grow to share space, min about 200px */
.box.wide { flex: 2; }           /* takes twice the share */
.box.last { margin-left: auto; } /* pushes this item to the far end */

Responsive card layout using Flexbox and a media query:

CSS
.cards { display: flex; flex-direction: column; gap: 16px; }   /* phone: stacked */
@media (min-width: 768px) {
  .cards { flex-direction: row; }                                /* tablet+: side by side */
  .card  { flex: 1; }
}

Extension: CSS Grid (display: grid; grid-template-columns: repeat(3, 1fr);) handles two-dimensional layouts. Flexbox is for one dimension, Grid for two.