DevAcademy
LearnCSSFlexbox
IntermediateCSS

Flexbox

Learn how to build flexible, one-dimensional layouts using the Flexbox model.

Reading Time

22 min

Lesson

Lesson 14 of 30

What is Flexbox?

Flexbox is a one-dimensional layout model designed for distributing space and aligning items along a row or a column. Turning on display: flex on a container makes its direct children flex items.

A Basic Flex Container

<style>
  .row {
    display: flex;
    gap: 10px;
  }
  .row div {
    background: steelblue;
    color: white;
    padding: 16px;
    flex: 1;
    text-align: center;
  }
</style>

<div class="row">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>
Output

Key Container Properties

PropertyPurpose
flex-directionMain axis direction: row, column, row-reverse, column-reverse
justify-contentAlignment along the main axis
align-itemsAlignment along the cross axis
flex-wrapWhether items wrap onto multiple lines
gapSpace between flex items

Centering with Flexbox

<style>
  .center-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 150px;
    background: #eef4fb;
  }
</style>

<div class="center-box">
  <div>Perfectly centered</div>
</div>
Output

Flex Item Properties

Individual flex items can control how they grow, shrink, and their base size using the flex shorthand, which combines flex-grow, flex-shrink, and flex-basis.

flex-grow in Action

<style>
  .layout {
    display: flex;
    gap: 10px;
  }
  .sidebar {
    flex: 0 0 150px; /* don't grow, don't shrink, fixed 150px */
    background: #764ba2;
    color: white;
    padding: 10px;
  }
  .main {
    flex: 1; /* grow to fill remaining space */
    background: #eef4fb;
    padding: 10px;
  }
</style>

<div class="layout">
  <div class="sidebar">Sidebar</div>
  <div class="main">Main content grows to fill space</div>
</div>
Output

justify-content Values

ValueEffect
flex-startItems packed at the start (default)
flex-endItems packed at the end
centerItems centered
space-betweenEqual space between items, none at the edges
space-aroundEqual space around each item

Wrapping Items

By default, flex items try to fit on a single line, shrinking if necessary. flex-wrap: wrap allows them to flow onto multiple lines instead.

Main Axis vs Cross Axis

With flex-direction: row, the main axis is horizontal and justify-content aligns along it, while align-items aligns along the vertical cross axis. Switching to flex-direction: column swaps these roles.

Best Practice

Reach for Flexbox whenever you need to align or distribute items along a single row or column — navbars, button groups, and centering content are classic use cases.

Interview Questions

Quick Quiz

1. Which property turns a container’s children into flex items?

2. Which property centers flex items along the main axis?

3. What does flex: 1 do to a flex item?