HTML & CSS - Mastery / Flexbox Mastery

Flex-direction Property

🧭 Flex Direction

The flex-direction property controls the direction in which flex items are laid out within a container. This is the first major step in shaping your layout using Flexbox.


Master code block to be used for further examples

<style>
    /*All the changes are made here further*/
    .flex-container {
      display: flex;
      background-color: lightgrey;
      padding: 10px;
    }
    .flex-item {
      background: steelblue;
      color: white;
      margin: 5px;
      padding: 20px;
      text-align: center;
    }
</style>

<div class="flex-container">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="flex-item">3</div>
</div>

🧱 Syntax

flex-direction: row | row-reverse | column | column-reverse;

🔀 Values Explained

▶️ row (Default)

  • Items are placed left to right (in horizontal row).

  • Main axis: horizontal

  • Cross axis: vertical

.flex-container {
  display: flex;
  flex-direction: row;
}

◀️ row-reverse

  • Items are placed right to left.

  • Order is reversed, but DOM structure remains the same.

  • Main axis: horizontal (reversed)

.flex-container {
  display: flex;
  flex-direction: row-reverse;
}

🔽 column

  • Items stack top to bottom (in vertical column).

  • Main axis: vertical

  • Cross axis: horizontal

.flex-container {
  display: flex;
  flex-direction: column;
}

🔼 column-reverse

  • Items stack bottom to top, reversing the visual flow.

  • Main axis: vertical (reversed)

.flex-container {
  display: flex;
  flex-direction: column-reverse;
}

🔀 Flex Direction Playground


🧭 Main Axis vs Cross Axis

Property

Main Axis Direction

Cross Axis Direction

row

➡ Left → Right

⬇ Top → Bottom

row-reverse

⬅ Right → Left

⬇ Top → Bottom

column

⬇ Top → Bottom

➡ Left → Right

column-reverse

⬆ Bottom → Top

➡ Left → Right

🔑 Main Axis = Flow of items

🔑 Cross Axis = Perpendicular to main axis

✅ These axes matter for properties like justify-content (main axis) and align-items (cross axis)


🛠️ Practical Layout Switches

Use Case

Flex-direction Value

Horizontal nav bar

row

Reverse nav bar for RTL language

row-reverse

Vertical sidebar menu

column

Chat app (latest message at bottom)

column-reverse


✅ Summary

  • flex-direction controls the flow direction of items in a Flexbox container.

  • You can switch from row to column layout easily with one line of CSS.

  • Understanding main and cross axis is crucial for aligning and distributing space later.