Flexbox arranges items in one direction (a row or a column), handling spacing, alignment and wrapping automatically.
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 */- Container properties:
display,flex-direction,flex-wrap,justify-content,align-items,gap. - Item properties:
flex-grow,flex-shrink,flex-basis(combined asflex),align-self,order. - Centre anything perfectly:
display:flex; justify-content:center; align-items:center; height:100vh;
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; }
}Make the browser window narrower or wider to see the layout change.
Card 1
Card 2
Card 3
Extension: CSS Grid (display: grid; grid-template-columns: repeat(3, 1fr);) handles two-dimensional layouts. Flexbox is for one dimension, Grid for two.