Lesson 6 of 6 · HTML + CSS

Flexbox and responsive layouts

Modern pages must work on wide screens and phones. Learn the basic Flexbox controls, spacing with gap and a media query that changes the layout when the screen becomes narrow.

Start a flex layout

Set display: flex on a container to arrange its direct children along a main axis. By default, items sit in a row. Use flex-direction: column when they should stack vertically.

justify-content controls distribution along the main axis, while align-items controls alignment across the cross axis. The result depends on the chosen flex direction.

Spacing and wrapping

Use gap to create consistent space between flex items without adding margins to every child. Set flex-wrap: wrap when items should move onto another line if there is not enough room.

Give flexible children sensible sizing. A card row can use flex: 1 1 220px so each card can grow, shrink and wrap around a useful base width.

Make the page responsive

A media query applies styles only when a condition is met, such as a maximum viewport width. At a smaller width, you might stack a navigation area, make cards full width or reduce a large heading size.

Responsive design is not just about shrinking everything. Check line length, tap target sizes, overflow and reading order. Test the page at several widths rather than one desktop and one phone preset.

index.html
<div class="card-row">
  <article class="card">HTML basics</article>
  <article class="card">CSS styling</article>
  <article class="card">Responsive design</article>
</div>
style.css
.card-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 18px;
}

.card {
  flex: 1 1 220px;
  padding: 24px;
  border-radius: 16px;
  background: #f0efff;
}

@media (max-width: 600px) {
  .card-row {
    flex-direction: column;
  }
}

Try it yourself

The code examples above are for reference. Copy the relevant example into the editor, press Run, then change it and run it again.

Code Campus
Your turn

Build a row of three cards using Flexbox. Let the cards wrap on smaller screens and switch to a vertical stack below 600 pixels.

Show a hint
.card-row { display: flex; flex-wrap: wrap; gap: 16px; }
.card { flex: 1 1 220px; }
@media (max-width: 600px) { .card-row { flex-direction: column; } }

#CodeCampus

Code Campus