CSS

Reorder Flex Items for Visual and Accessibility Control with order

Learn to leverage the CSS `order` property in Flexbox to change the visual sequence of items independently of their source order for design flexibility and accessibility.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flex Item Reordering</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="flex-container">
        <div class="flex-item item-alpha">Item Alpha (order: 0, default)</div>
        <div class="flex-item item-beta">Item Beta (order: 3)</div>
        <div class="flex-item item-gamma">Item Gamma (order: 1)</div>
        <div class="flex-item item-delta">Item Delta (order: -1)</div>
    </div>
    <p>Observe the visual order of items compared to their HTML source order.</p>
    <p>Default order for flex items is 0. Lower 'order' values appear first.</p>
</body>
</html>

body {
    font-family: sans-serif;
    margin: 20px;
    background-color: #f4f4f4;
}

.flex-container {
    display: flex;
    border: 2px solid #333;
    padding: 10px;
    background-color: #fff;
    min-height: 150px;
    justify-content: center;
    align-items: center;
    gap: 10px; /* Space between items */
    flex-wrap: wrap; /* Allow items to wrap if container is too small */
}

.flex-item {
    padding: 15px;
    background-color: #007bff;
    color: white;
    text-align: center;
    border-radius: 5px;
    min-width: 150px;
}

/* Items are in source order by default.
   The 'order' property changes their visual position.
   Lower 'order' values appear earlier. Default is 0. */

.item-alpha {
    /* order: 0; (default) */
    background-color: #28a745;
}

.item-beta {
    order: 3; /* This item will appear after items with order 0, 1, 2 */
    background-color: #ffc107;
    color: #333;
}

.item-gamma {
    order: 1; /* This item will appear after items with order 0, but before order 3 */
    background-color: #6f42c1;
}

.item-delta {
    order: -1; /* This item will appear first as it has the lowest order */
    background-color: #dc3545;
}
How it works: This snippet demonstrates the `order` property in Flexbox, which allows you to change the visual display order of flex items independently of their order in the HTML source code. By default, all flex items have an `order` of `0`. Items with a lower `order` value appear before items with a higher value. If multiple items share the same `order` value, their original source order is maintained. This is incredibly useful for responsive design, where the visual arrangement might need to change for different screen sizes, or for accessibility purposes, ensuring the logical DOM order is preserved while adapting the visual layout.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs