Flexbox Basics
The modern way to lay out rows and columns. Flexbox makes alignment and spacing effortless.
What you will learn
- Create a flex container
- Align items with justify-content and align-items
- Control direction, wrapping and gaps
Turn any element into a flex container
Set display: flex on a parent and its children become flexible items laid out in a row. Then a few properties control everything.
| Property (on the container) | Controls |
|---|---|
flex-direction | Row or column (row, column) |
justify-content | Spacing along the MAIN axis |
align-items | Alignment on the CROSS axis |
gap | Space between items |
flex-wrap | Let items wrap to the next line |
<style>
.row { display: flex; justify-content: space-between; align-items: center; gap: 12px;
background:#e0e7ff; padding:14px; border-radius:10px; }
.row > div { background:#4338ca; color:#fff; padding:14px 18px; border-radius:8px; }
</style>
<div class="row">
<div>One</div>
<div>Two</div>
<div>Three</div>
</div>The moment .row gets display: flex, its three child <div>s line up in a row instead of stacking. Then the container properties arrange them: justify-content: space-between pushes the items to the two ends and spreads the leftover space between them, align-items: center lines them up vertically, and gap: 12px guarantees a minimum 12px space between items. Change justify-content and the spacing pattern changes — that is the next example.
justify-content values
flex-start, center, flex-end, space-between, space-around, space-evenly — try each to see how items spread along the row.
<style>
.cards { display: flex; gap: 12px; flex-wrap: wrap; }
.card { flex: 1; min-width: 120px; background:#fff; border:1px solid #e6e8f0;
border-radius:12px; padding:16px; }
</style>
<div class="cards">
<div class="card"><h4>Plan A</h4><p>Cheap</p></div>
<div class="card"><h4>Plan B</h4><p>Popular</p></div>
<div class="card"><h4>Plan C</h4><p>Pro</p></div>
</div>This is the everyday card-row pattern. On the container, display: flex rows the cards up, gap: 12px spaces them, and flex-wrap: wrap lets cards drop to a new line when there is no room. On each card, flex: 1 means “grow to share the space equally”, so the three cards become equal widths; min-width: 120px stops them from shrinking too far before they wrap. Resize the preview narrow and you will see the cards stack instead of squashing.
Tip: Two axes: justify-content moves items along the main axis (left↔right in a row); align-items moves them on the cross axis (top↕bottom in a row). Say it until it sticks.
Q. In a flex row, which property spaces items horizontally?
✍️ Practice
- Build a navbar with the logo on the left and links on the right using
justify-content: space-between. - Build a row of three equal cards that wrap on small screens.
🏠 Homework
- Rebuild your landing page’s feature section as a flex row of cards.