CSS

Control Flex Item Order and Distribute Space Evenly

Learn to reorder flex items independently of their source order and distribute remaining space efficiently using `order` and `justify-content` properties for precise layouts.

/* HTML Structure */
/*
<div class="flex-container">
  <div class="flex-item item-a">Item A (Order 3)</div>
  <div class="flex-item item-b">Item B (Order 1)</div>
  <div class="flex-item item-c">Item C (Order 2)</div>
  <div class="flex-item item-d">Item D (Order 4)</div>
</div>
*/

/* CSS */
.flex-container {
  display: flex;
  /* Distributes items with equal space around each, and half that space at the ends */
  justify-content: space-evenly; 
  /* Other options: space-between, space-around, flex-start, flex-end, center */
  border: 2px dashed #9c27b0;
  padding: 10px;
  min-height: 100px;
  background-color: #f3e5f5;
}

.flex-item {
  background-color: #e1bee7;
  border: 1px solid #7b1fa2;
  padding: 1rem;
  margin: 5px;
  color: #333;
  border-radius: 5px;
}

.item-a {
  order: 3; /* Default order is 0 */
}

.item-b {
  order: 1;
}

.item-c {
  order: 2;
}

.item-d {
  order: 4;
}
How it works: This snippet illustrates how to manipulate the visual order of flex items and control their spacing within a container. The `order` property on individual flex items allows you to change their display sequence independently of their order in the HTML source, with lower values appearing first. The `justify-content: space-evenly` property on the flex container ensures that items are distributed with equal space between them and equal space at the start and end of the main axis, offering precise control over horizontal spacing. Other `justify-content` values (`space-between`, `space-around`, `center`, etc.) provide different distribution patterns.

Need help integrating this into your project?

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

Hire DigitalCodeLabs