Web Development · Module 4 · Lesson 11 min read

Flexbox

One-dimensional layout

Flexbox arranges items in a row or a column and handles spacing and alignment for you. Make the parent a flex container:

CSS
.container { display: flex; }

Container properties

PropertyWhat it doesCommon values
flex-directionmain axisrow (default), column
justify-contentalignment along the main axisflex-start, center, space-between, space-around
align-itemsalignment on the cross axisstretch, center, flex-start
gapspace between items16px
flex-wrapallow new lineswrap

Item properties

  • flex: 1 takes an equal share of the free space.
  • flex: 0 0 200px is a fixed 200 px that won't grow or shrink.
  • align-self overrides alignment for one item.
  • order changes the visual order (keep it rare for accessibility).

Patterns you'll use constantly

  • Centre anything: display: flex; justify-content: center; align-items: center;
  • Navbar: logo left, links right with justify-content: space-between.
  • Push one item right: give it margin-left: auto.
  • Wrapping cards: flex-wrap: wrap; gap: 16px;, with children flex: 1 1 250px;.

Example

HTML
<style>
  body { font-family: sans-serif; margin: 0; }
  .nav {
    display: flex; justify-content: space-between; align-items: center;
    padding: 12px 20px; background: #111827; color: white;
  }
  .nav ul { display: flex; gap: 16px; list-style: none; margin: 0; padding: 0; }
  .cards { display: flex; flex-wrap: wrap; gap: 16px; padding: 20px; }
  .card {
    flex: 1 1 200px;
    padding: 20px; border-radius: 12px; background: #eef2ff;
  }
  .center { display: flex; justify-content: center; align-items: center; height: 120px; background: #f3f4f6; }
</style>

<nav class="nav">
  <strong>Logo</strong>
  <ul><li>Home</li><li>Blog</li><li>Contact</li></ul>
</nav>
<div class="cards">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
</div>
<div class="center">Perfectly centred</div>