CSS

Reorder Flex Items Visually Using the Order Property

Learn to change the visual sequence of flex items without altering their HTML source order, perfect for responsive design adjustments or accessibility considerations.

.flex-container {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  gap: 10px;
  font-family: sans-serif;
  flex-wrap: wrap; /* Allows items to wrap on smaller screens */
}

.flex-item {
  background-color: #007bff;
  color: white;
  padding: 15px;
  border-radius: 5px;
  font-size: 1.2em;
  flex-basis: 120px; /* Base width for items */
  text-align: center;
}

/* Reordering items */
.item-a { order: 2; }
.item-b { order: 1; }
.item-c { order: 4; }
.item-d { order: 3; }

/* Default order is 0. Smaller 'order' values come first. */
/* Original HTML order: Item A, Item B, Item C, Item D */
/* Visual order with CSS: Item B, Item A, Item D, Item C */

/* Basic HTML structure for context */
/*
<div class="flex-container">
  <div class="flex-item item-a">Item A</div>
  <div class="flex-item item-b">Item B</div>
  <div class="flex-item item-c">Item C</div>
  <div class="flex-item item-d">Item D</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 modifying their order in the HTML source. By default, all flex items have `order: 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 preserved. This is particularly useful for responsive designs where the visual flow of content needs to change at different screen sizes without impacting accessibility or SEO by altering the document structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs