In the HTML, your elements appear in a certain order. But with flexbox, you can change the
visual order without touching the HTML. The order property lets you rearrange
flex items however you want.
This is incredibly powerful for responsive designs. On desktop you might want a sidebar on the
left, but on mobile you want it below the main content. Instead of duplicating HTML and hiding
one copy, you can just use order.
How Order Works
Every flex item has a default order value of 0. Items with lower numbers come
first, and items with the same number appear in source order. You can use positive or negative
numbers.
.item-first {
order: -1;
}
.item-second {
order: 0;
}
.item-third {
order: 1;
}
The item with order: -1 will appear before everything else, even though it might
come later in the HTML. Items with the same order value maintain their original HTML order.
Responsive Reordering
Here is a real-world scenario. You have a layout with a header, sidebar, and main content. On desktop, the sidebar is on the left. On mobile, you want it below the content. You can do this with media queries and the order property.
.layout {
display: flex;
}
.sidebar {
order: 0;
}
.main {
order: 1;
}
@media (max-width: 768px) {
.layout {
flex-direction: column;
}
.sidebar {
order: 2;
}
}
On desktop, the sidebar stays at order 0 (first). On mobile, the flex direction changes to column and the sidebar gets order 2, pushing it below the main content. No HTML changes needed.
Keep It Simple
While the order property is powerful, use it sparingly. Overusing it can make your layout confusing to maintain. If you find yourself reordering everything, consider whether a different HTML structure might be clearer. The best layouts are those where the visual order matches the source order.