CSS

Dynamically Reorder Elements with CSS Flexbox `order` Property

Change the visual order of flex items independently of their source order in the HTML using the `order` property, useful for responsive designs, accessibility adjustments, or A/B testing layouts.

.flex-container {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  gap: 10px;
  font-family: sans-serif;
}

.item {
  padding: 15px;
  background-color: lightgoldenrodyellow;
  border: 1px solid goldenrod;
}

/* Override default order (which is 0) */
.item-a { order: 2; background-color: #b3e0ff; }
.item-b { order: 1; background-color: #ffe0b3; }
.item-c { order: 3; background-color: #b3ffb3; }
.item-d { order: 0; background-color: #ffd4e5; } /* Explicitly set to default */

/* HTML Structure:
<div class="flex-container">
  <div class="item item-d">Item D (Original 1st in HTML)</div>
  <div class="item item-a">Item A (Original 2nd in HTML)</div>
  <div class="item item-b">Item B (Original 3rd in HTML)</div>
  <div class="item item-c">Item C (Original 4th in HTML)</div>
</div>
*/
How it works: This snippet showcases how the `order` property in CSS Flexbox allows you to visually reorder items within a flex container without altering their underlying HTML structure. By default, all flex items have an `order` value of `0`. Items are displayed in ascending order of their `order` value. By assigning different integer values to `order` on individual flex items (e.g., `order: 1`, `order: 2`), you can change their visual sequence, which is incredibly useful for responsive layouts or accessibility considerations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs