0
0
CssHow-ToBeginner · 3 min read

How to Use Order in Flexbox: Simple CSS Guide

Use the order property on flex items to change their visual order within a flex container. Items with lower order values appear first, regardless of their HTML position. The default order value is 0.
📐

Syntax

The order property accepts an integer value that sets the order of a flex item within its container. Items with smaller values appear before items with larger values.

  • order: 0; — default order.
  • order: 1; — appears after items with order 0.
  • order: -1; — appears before items with order 0.
css
/* Syntax for order property */
.flex-item {
  order: <integer>;
}
💻

Example

This example shows three boxes in a row. The HTML order is Box 1, Box 2, Box 3, but using order changes their visual order to Box 3, Box 1, Box 2.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Flexbox Order Example</title>
<style>
  .container {
    display: flex;
    gap: 1rem;
  }
  .box {
    padding: 1rem 2rem;
    background-color: #4a90e2;
    color: white;
    font-weight: bold;
    border-radius: 0.5rem;
  }
  .box1 {
    order: 1;
  }
  .box2 {
    order: 2;
  }
  .box3 {
    order: 0;
  }
</style>
</head>
<body>
  <div class="container">
    <div class="box box1">Box 1</div>
    <div class="box box2">Box 2</div>
    <div class="box box3">Box 3</div>
  </div>
</body>
</html>
Output
Three colored boxes in a row: first 'Box 3' on the left, then 'Box 1' in the middle, and 'Box 2' on the right.
⚠️

Common Pitfalls

One common mistake is expecting order to change the HTML source order, but it only changes visual order. This can affect keyboard navigation and screen readers if not handled carefully.

Another pitfall is using negative or very large order values without a clear plan, which can make layout confusing.

css
/* Wrong: expecting HTML order to change */
/* Right: use order only for visual rearrangement */

.container {
  display: flex;
}

.item1 {
  order: 2; /* appears last visually */
}
.item2 {
  order: 1; /* appears second visually */
}
.item3 {
  order: 0; /* appears first visually */
}
📊

Quick Reference

Order Property Cheat Sheet:

  • order: 0; — default position.
  • order: 1; — after default items.
  • order: -1; — before default items.
  • Lower order values appear first.
  • Does not affect HTML source order.

Key Takeaways

The CSS order property changes the visual order of flex items without altering HTML.
Items with lower order values appear before those with higher values.
Default order is 0; use positive or negative integers to reorder.
Changing order does not affect keyboard or screen reader navigation.
Use order carefully to keep layout clear and accessible.