CodeMIRAI
0 XP

Flexbox

2 min read 5 runnable examples Quiz included

Flexbox lays items out in one direction, a row or a column, and makes spacing and alignment easy. It's the go-to tool for navigation bars, toolbars, cards in a row and centring things.

Turning it on

Set display: flex on the container. Its direct children become flex items and line up in a row:

HTML
<style>
  .row { display: flex; gap: 10px; font-family: system-ui; }
  .row div { background: #eef0ff; border: 2px solid #5a48f5; padding: 14px; border-radius: 8px; }
</style>
<div class="row">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

gap sets the space between items, with no margin arithmetic needed.

Direction

HTML
<style>
  .col { display: flex; flex-direction: column; gap: 8px; max-width: 200px; font-family: system-ui; }
  .col div { background: #e6f9ff; padding: 10px; border-radius: 6px; }
</style>
<div class="col"><div>Top</div><div>Middle</div><div>Bottom</div></div>
display: flexitem 1item 2item 3main axis: justify-contentcross axis: align-items
With flex-direction: row the main axis runs across and the cross axis down; column swaps them.

flex-direction can be row (the default), column, row-reverse or column-reverse.

Wrapping

By default, items squeeze onto one line. flex-wrap: wrap lets them flow onto new lines when there isn't room:

HTML
<style>
  .wrap { display: flex; flex-wrap: wrap; gap: 8px; max-width: 360px; font-family: system-ui; }
  .wrap span { background: #fff4dc; padding: 6px 12px; border-radius: 999px; }
</style>
<div class="wrap">
  <span>Python</span><span>JavaScript</span><span>SQL</span><span>React</span>
  <span>CSS</span><span>Java</span><span>C++</span><span>PHP</span>
</div>

Growing and shrinking

flex: 1 makes an item take up the free space. Give several items flex: 1 and they share it equally:

HTML
<style>
  .bar { display: flex; gap: 8px; font-family: system-ui; }
  .bar > * { padding: 12px; border-radius: 8px; background: #eef0ff; }
  .grow { flex: 1; background: #d9f7ea !important; }
</style>
<div class="bar">
  <div>Logo</div>
  <div class="grow">I grow to fill the space</div>
  <div>Menu</div>
</div>

That "logo, space, menu" pattern is the skeleton of most website headers.

A navigation bar

HTML
<style>
  nav { display: flex; align-items: center; gap: 18px; padding: 12px 18px; background: #11151f; border-radius: 10px; font-family: system-ui; }
  nav a { color: #e9ecf5; text-decoration: none; }
  nav .brand { font-weight: 800; margin-right: auto; color: #8577ff; }
</style>
<nav>
  <a class="brand" href="#">CodeMIRAI</a>
  <a href="#">Courses</a>
  <a href="#">Practice</a>
  <a href="#">Sign in</a>
</nav>

margin-right: auto on the brand pushes everything after it to the right.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.