CSS

Dynamically Reorder Flex Items with the `order` Property for Responsive Layouts

Learn how to change the visual order of elements within a Flexbox container independently of their source HTML order using the `order` property, ideal for responsive design adjustments.

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

.flex-item {
  background-color: #e0f7fa;
  padding: 15px;
  text-align: center;
  flex-basis: 120px; /* Base width */
}

/* Default order */
.item-1 { order: 1; background-color: #ffe0b2; }
.item-2 { order: 2; background-color: #c8e6c9; }
.item-3 { order: 3; background-color: #ffccbc; }

/* Reorder for smaller screens */
@media (max-width: 600px) {
  .flex-container {
    flex-direction: column;
  }
  .item-1 { order: 3; } /* item-1 moves to bottom */
  .item-2 { order: 1; } /* item-2 moves to top */
  .item-3 { order: 2; } /* item-3 moves to middle */
}
How it works: This snippet demonstrates the powerful `order` property in Flexbox, allowing you to control the visual display order of flex items independently of their source HTML order. By assigning different `order` values, and changing them within a media query, you can achieve sophisticated responsive reordering of content. Lower `order` values appear first.

Need help integrating this into your project?

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

Hire DigitalCodeLabs