Lesson 5 of 8 · 14 min · 1 hands-on step

CSS Layout with Flexbox

Style pages and lay them out with the box model and Flexbox.

Selecting and styling

CSS rules have a selector and declarations:

.card {
  padding: 16px;
  border-radius: 12px;
  background: white;
}

Common selectors: p (tag), .card (class), #hero (id, use sparingly), .nav a (links inside .nav).

The box model

Every element is a box: content → padding → border → margin. Add this once at the top of every project so widths behave the way you expect:

* { box-sizing: border-box; }

Flexbox

Flexbox lays items out in a row or column:

.row {
  display: flex;
  gap: 16px;               /* space between items */
  justify-content: space-between; /* main axis */
  align-items: center;     /* cross axis */
}

Use flex-direction: column for vertical stacks and flex-wrap: wrap to let items move to the next line on small screens.

Responsive design

Most of your users are on phones. Start with the mobile layout, then add media queries for bigger screens:

.grid { display: grid; gap: 16px; }
@media (min-width: 768px) {
  .grid { grid-template-columns: 1fr 1fr; }
}

🧪 Practice

Turn the vertical list of links into a horizontal navigation bar:

  • Make .nav a flex container
  • Put 16px of gap between links
  • Vertically center items with align-items: center
<nav class="nav">
  <a href="#">Home</a>
  <a href="#">Projects</a>
  <a href="#">About</a>
  <a href="#">Contact</a>
</nav>

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. In the box model, what sits between the content and the border?

  2. Which property sets the direction of a flex container?

Create a free account to track your progress.