CSS
Flexbox/Grid: Dynamically Reorder Elements with `order` Property
Learn how to easily change the visual order of elements in Flexbox or CSS Grid without altering HTML markup using the `order` property.
/* Flexbox Example */
.flex-container {
display: flex;
gap: 10px;
border: 1px solid #ddd;
padding: 10px;
margin-bottom: 20px;
}
.flex-item {
background-color: #28a745;
color: white;
padding: 15px;
border-radius: 5px;
font-weight: bold;
flex-basis: 100px; /* Give items a base width */
text-align: center;
}
.flex-item.first { order: 2; } /* Visually appears after default-ordered items (order: 0) */
.flex-item.second { order: 1; } /* Visually appears before .first but after default */
.flex-item.last { order: -1; } /* Visually appears before all other items */
/* Grid Example */
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
border: 1px solid #ddd;
padding: 10px;
}
.grid-item {
background-color: #ffc107;
color: #333;
padding: 15px;
border-radius: 5px;
font-weight: bold;
text-align: center;
}
.grid-item.promo {
grid-column: span 2; /* Spans two columns */
order: -1; /* Appears first in the flow */
background-color: #17a2b8;
color: white;
}
.grid-item.ad {
order: 10; /* Appears last in the flow */
background-color: #dc3545;
color: white;
}
/* Media query to reorder for mobile */
@media (max-width: 600px) {
.flex-container {
flex-direction: column;
}
.flex-item.first { order: 1; } /* Reset to default order for mobile */
.flex-item.second { order: 2; }
.flex-item.last { order: 3; }
.grid-container {
grid-template-columns: 1fr; /* Single column layout */
}
.grid-item.promo, .grid-item.ad {
grid-column: span 1; /* Reset column span */
order: unset; /* Remove specific order for mobile, revert to source order */
}
}
<!-- HTML -->
<h3>Flexbox Order Example</h3>
<div class="flex-container">
<div class="flex-item">Default Order 0 (1)</div>
<div class="flex-item second">Second (order: 1)</div>
<div class="flex-item first">First (order: 2)</div>
<div class="flex-item last">Last (order: -1)</div>
<div class="flex-item">Default Order 0 (2)</div>
</div>
<h3>Grid Order Example</h3>
<div class="grid-container">
<div class="grid-item">Grid Item A</div>
<div class="grid-item promo">Promo Offer (order: -1, span 2)</div>
<div class="grid-item">Grid Item B</div>
<div class="grid-item ad">Advert (order: 10)</div>
<div class="grid-item">Grid Item C</div>
</div>
How it works: This snippet illustrates how to use the `order` property in both Flexbox and CSS Grid to change the visual sequence of items without modifying their order in the HTML. By default, all items have `order: 0`. Items with a lower `order` value appear before items with a higher value. Negative values (`-1`) place elements at the very beginning, while positive values (`1`, `2`, `10`) push them towards the end. This is particularly useful for responsive design, allowing content to be reordered on different screen sizes using media queries for better user experience.