CSS
Visually Reorder Flex Items with the `order` Property
Discover how to use the CSS `order` property in Flexbox to change the visual sequence of items on a page without altering their underlying HTML structure.
.flex-container {
display: flex;
border: 2px dashed #9b59b6;
padding: 15px;
background-color: #f8f0fc;
gap: 10px;
}
.flex-item {
background-color: #9b59b6;
color: white;
padding: 15px 20px;
font-family: sans-serif;
font-weight: bold;
border-radius: 4px;
font-size: 1.1em;
}
/* Specific order for items */
.flex-item:nth-child(1) { order: 3; } /* Item 1 will appear third */
.flex-item:nth-child(2) { order: 1; } /* Item 2 will appear first */
.flex-item:nth-child(3) { order: 4; } /* Item 3 will appear fourth */
.flex-item:nth-child(4) { order: 2; } /* Item 4 will appear second */
/* Example usage in HTML:
<div class="flex-container">
<div class="flex-item">One</div>
<div class="flex-item">Two</div>
<div class="flex-item">Three</div>
<div class="flex-item">Four</div>
</div>
Original HTML order: One, Two, Three, Four
Visual order with CSS: Two, Four, One, Three
*/
How it works: This snippet illustrates the use of the `order` property in Flexbox. By default, flex items are arranged in the order they appear in the source HTML (their `order` value is 0). By assigning positive or negative integer values to the `order` property on individual flex items, you can change their visual sequence within the flex container. Items with lower `order` values appear first. This is incredibly useful for responsive design where the visual presentation needs to differ from the logical HTML structure for accessibility or SEO purposes.