CSS
Dynamically Reorder Flex Items with CSS `order`
Learn how to visually change the order of flex items independently of their source HTML order using the `order` CSS property, useful for responsive design.
.container {
display: flex;
gap: 10px;
background-color: #e6f7ff;
padding: 15px;
border: 1px solid #b3e0ff;
}
.item {
background-color: #008cba;
color: white;
padding: 10px 15px;
border-radius: 5px;
font-family: sans-serif;
/* Default order */
order: 0;
}
/* Example of reordering: item 2 comes first visually */
.item-1 { order: 2; }
.item-2 { order: 1; }
.item-3 { order: 3; }
/* Media query to change order on smaller screens */
@media (max-width: 600px) {
.item-1 { order: 3; }
.item-2 { order: 2; }
.item-3 { order: 1; } /* Item 3 moves to the front */
}
<div class="container">
<div class="item item-1">Item 1</div>
<div class="item item-2">Item 2</div>
<div class="item item-3">Item 3</div>
</div>
How it works: This snippet demonstrates the `order` property in Flexbox, which allows you to change the visual sequence of flex items without altering their order in the HTML source. Items with a lower `order` value appear earlier in the container. By default, items have `order: 0`. Assigning custom `order` values lets you easily reconfigure layouts, for example, moving a sidebar or primary content to a different position based on screen size, as shown with the media query.