CSS
Reordering Flex Items without HTML Changes using `order`
Learn how to dynamically reorder elements within a Flexbox container using the CSS `order` property, enhancing responsiveness and accessibility for various screen sizes.
.flex-container {
display: flex;
flex-direction: row; /* Default */
}
.item-1 {
order: 2; /* Will appear after item with order 1 (or default 0) */
background-color: lightcoral;
padding: 10px;
margin: 5px;
}
.item-2 {
order: 3; /* Will appear after item with order 2 */
background-color: lightblue;
padding: 10px;
margin: 5px;
}
.item-3 {
order: 1; /* Will appear first among these three */
background-color: lightgreen;
padding: 10px;
margin: 5px;
}
/* Example HTML structure */
/*
<div class="flex-container">
<div class="item-1">Item A (originally first)</div>
<div class="item-2">Item B (originally second)</div>
<div class="item-3">Item C (originally third)</div>
</div>
*/
How it works: The `order` property in Flexbox allows you to change the visual order of flex items without altering their source HTML. By default, all flex items have an `order` of `0`. Items with lower `order` values appear before items with higher values. This is incredibly useful for responsive design, where content might need to be rearranged for different screen sizes or for accessibility purposes without impacting the document flow.