CSS
Reordering Flex Items with the order Property
Learn how to visually reorder flex items independently of their source HTML order, crucial for responsive layouts and accessibility considerations.
.flex-container-order {
display: flex;
width: 500px;
border: 2px solid #333;
padding: 10px;
gap: 10px;
}
.flex-item-order {
padding: 15px;
background-color: #f0f0f0;
border: 1px solid #ccc;
color: #555;
font-family: sans-serif;
text-align: center;
width: 100px; /* Fixed width for demonstration */
}
/* Default order is 0 */
.flex-item-order.alpha {
order: 2; /* Will appear after items with order 0 or 1 */
background-color: lightcoral;
}
.flex-item-order.beta {
order: 1; /* Will appear before item alpha but after default */
background-color: lightgreen;
}
.flex-item-order.gamma {
order: -1; /* Will appear first as it has the lowest order value */
background-color: lightblue;
}
.flex-item-order.delta {
/* No explicit order, defaults to 0 */
background-color: lightgoldenrodyellow;
}
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 HTML source. Items are displayed in ascending order based on their `order` value, with items having the same `order` value maintaining their original HTML order. This is incredibly useful for responsive design, allowing elements to shift positions on different screen sizes, or for accessibility, ensuring that the visual order aligns with a logical tab order for keyboard navigation.