The Flexbox Mental Model
Flexbox is about axes. Once you understand main axis vs cross axis, everything else falls into place.
Flexbox has TWO axes. The main axis is determined by flex-direction (row = horizontal, column = vertical). The cross axis is perpendicular. Every Flexbox property works on one of these axes.
Core concept: flex-direction sets main axis. Cross axis is always perpendicular.
flex-direction
justify-content
align-items
flex-wrap
gap
flex-shrink
flex-basis
align-self
order
Add display: flex to a parent element — it becomes the flex container. Its direct children automatically become flex items. Container properties control layout; item properties control individual behavior.
Key distinction: Parent = container properties. Children = item properties.
overflow: hidden; /* clearfix */
}
.item {
float: left;
width: 33.333%;
box-sizing: border-box;
}
.item:nth-child(3n+1) {
clear: left;
}
display: flex;
gap: 16px;
flex-wrap: wrap;
}
/* That's it! */
Before Flexbox, we used floats, clearfixes, and table-cell hacks. Vertical centering was notoriously difficult. Flexbox solved these problems elegantly.
History: Flexbox replaced years of layout hacks with simple, logical properties