HTML and CSS · Lesson 8 of 12

Flexbox

Flexbox lays things out in one direction, a row or a column, and handles the spacing and alignment that used to need hacks.

The container

display: flex on a parent makes its children flex items, laid out in a row by default (flex-direction: column for a column). Then:

  • justify-content spreads them along the main direction: flex-start, center, space-between.
  • align-items aligns them across it: stretch, center, flex-start.
  • gap puts space between them; flex-wrap: wrap lets them move to a new line.
Try itEdit the code: the page updates as you type

The items

flex: 1 lets an item grow to fill the space left. In full it's flex-grow (take extra space), flex-shrink (give up space) and flex-basis (the starting size). margin-left: auto on one item pushes it, and everything after it, to the far end.

The classic: centring anything, both ways: display: flex; justify-content: center; align-items: center; on the parent.

Try itEdit the code: the page updates as you type

Your turn

Make a row of three cards of equal width with 16px between them, that wrap onto new lines on a narrow screen (each card at least 160px wide).

ExerciseEdit the code: the page updates as you type
Show a solution
<style>
  .cards { display: flex; flex-wrap: wrap; gap: 16px; }
  .card { flex: 1 1 160px; background: #e7f5ff; padding: 16px; border-radius: 10px; }
</style>
<div class="cards">
  <div class="card">DSA</div>
  <div class="card">Core CS</div>
  <div class="card">Aptitude</div>
</div>

In the interview

How do you centre a div horizontally and vertically?

On the parent: display: flex; justify-content: center; align-items: center (or display: grid; place-items: center). The parent needs a height for vertical centring to show.

justify-content vs align-items?

justify-content aligns items along the main axis (the row direction by default); align-items aligns them across it. Switching flex-direction to column swaps which one is horizontal.

What does flex: 1 mean?

flex-grow: 1, flex-shrink: 1, flex-basis: 0%: the item starts from nothing and takes an equal share of the free space, so several flex: 1 items end up the same size.

Your progress stays on this device.