CSS

Dynamically Reordering Flex or Grid Items with the `order` Property

Control the visual sequence of elements independently of their source order using the CSS `order` property in Flexbox and Grid, ideal for responsive design and accessibility adjustments.

/* Flexbox Container */
.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: 400px;
  border: 1px solid #ccc;
  padding: 10px;
}

/* Default order (based on source order) */
.flex-item {
  padding: 15px;
  background-color: lightblue;
  border: 1px solid blue;
  flex: 1 1 auto; /* Allow items to grow/shrink */
}

/* Custom Order: Smaller 'order' values appear earlier */
.flex-item.first {
  order: -1; /* Appears first */
  background-color: lightcoral;
}

.flex-item.middle {
  order: 1;  /* Appears after items with default order (0) or smaller */
}

.flex-item.last {
  order: 2;  /* Appears last */
  background-color: lightgreen;
}

/* Grid items can also use 'order' if not explicitly placed by grid-column/row */
.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  width: 400px;
  border: 1px solid #ccc;
  padding: 10px;
}

.grid-container > div {
  padding: 15px;
  background-color: lightgoldenrodyellow;
  border: 1px solid orange;
}

.grid-container .grid-first {
  order: -1; /* Will appear before others */
  background-color: lightseagreen;
}

.grid-container .grid-last {
  order: 1; /* Will appear after others */
  background-color: lightpink;
}
How it works: The `order` property in CSS Flexbox and Grid allows you to change the visual sequence of items independently of their order in the HTML source. By default, all items have `order: 0;`. Items with smaller `order` values appear earlier, while items with larger values appear later. If multiple items have the same `order` value, their original source order is preserved among themselves. This is incredibly useful for responsive design, enabling you to re-arrange content for different screen sizes without altering the underlying HTML, which can be beneficial for accessibility as the logical (source) order remains intact.

Need help integrating this into your project?

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

Hire DigitalCodeLabs