CSS

Dynamically Reorder Elements with Flexbox `order` Property

Discover how to easily change the visual display order of flex items independently of their source HTML order using the `order` property, ideal for responsive layouts.

.flex-container {
  display: flex;
  flex-direction: row; /* Default: items displayed left to right */
  gap: 10px;
}

.item {
  padding: 15px;
  border: 1px solid #ccc;
  background-color: #f0f0f0;
}

/* Default order */
.item-a { order: 1; }
.item-b { order: 2; }
.item-c { order: 3; }

@media (max-width: 768px) {
  .flex-container {
    flex-direction: column; /* Stack items vertically on smaller screens */
  }
  .item-a { order: 3; } /* Move item A to the bottom */
  .item-b { order: 1; } /* Move item B to the top */
  .item-c { order: 2; } /* Keep item C in the middle */
}
How it works: The `order` property in Flexbox allows you to control the visual sequence of flex items, overriding their natural order in the HTML source. By default, all flex items have an `order` value of `0`. Items with lower `order` values appear before items with higher values. This snippet demonstrates how to assign specific `order` values to items and then dynamically change these values within a media query, enabling you to re-arrange your layout for different screen sizes without modifying the HTML structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs