CSS
Reordering Flexbox Items with the `order` Property
Discover how to easily change the visual order of Flexbox items independently of their source HTML order, perfect for responsive design.
/* HTML Structure:
<div class="flex-container-order">
<div class="flex-item-order item-a">Item A</div>
<div class="flex-item-order item-b">Item B</div>
<div class="flex-item-order item-c">Item C</div>
<div class="flex-item-order item-d">Item D</div>
</div>
*/
.flex-container-order {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
gap: 15px;
padding: 20px;
border: 1px dashed #ccc;
}
.flex-item-order {
background-color: #add8e6;
padding: 20px;
border: 1px solid #87ceeb;
flex-basis: 150px; /* Minimum width for items */
flex-grow: 1; /* Allow items to grow to fill space */
text-align: center;
font-weight: bold;
}
/* Default order is 0. Items with lower order appear first. */
.item-a { order: 2; background-color: lightcoral; }
.item-b { order: 4; background-color: lightgreen; }
.item-c { order: 1; background-color: lightgoldenrodyellow; }
.item-d { order: 3; background-color: lightsalmon; }
/* Example: Reordering on smaller screens using media queries */
@media (max-width: 600px) {
.flex-container-order {
flex-direction: column; /* Stack items vertically */
}
.item-a { order: 1; } /* Item A first */
.item-b { order: 3; } /* Item B third */
.item-c { order: 2; } /* Item C second */
.item-d { order: 4; } /* Item D last */
}
How it works: The `order` property in Flexbox allows you to change the visual display order of flex items, regardless of their order in the source HTML. By default, all flex items have `order: 0`. Items with a lower `order` value appear before items with a higher value. If multiple items have the same `order` value, their original source order is maintained. This is incredibly useful for responsive designs where content needs to be reordered on different screen sizes without modifying the HTML markup, improving accessibility and maintainability.