CSS

Distributing Flex Items with justify-content

Master the `justify-content` property in Flexbox to control the spacing and alignment of items along the main axis, creating balanced layouts.

/* HTML Structure: */
/* <div class="flex-container-spaceBetween">
/*   <div class="flex-item">1</div>
/*   <div class="flex-item">2</div>
/*   <div class="flex-item">3</div>
/* </div>
/* <div class="flex-container-spaceAround">
/*   <div class="flex-item">1</div>
/*   <div class="flex-item">2</div>
/*   <div class="flex-item">3</div>
/* </div>
/* <div class="flex-container-spaceEvenly">
/*   <div class="flex-item">1</div>
/*   <div class="flex-item">2</div>
/*   <div class="flex-item">3</div>
/* </div> */

.flex-container-spaceBetween {
  display: flex;
  justify-content: space-between;
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
}

.flex-container-spaceAround {
  display: flex;
  justify-content: space-around;
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
}

.flex-container-spaceEvenly {
  display: flex;
  justify-content: space-evenly;
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
}

.flex-item {
  width: 80px;
  height: 50px;
  background-color: #a0d0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
}
How it works: This snippet illustrates different ways to distribute space between flex items along the main axis using `justify-content`. `space-between` places the first item at the start and the last item at the end, distributing remaining space evenly between them. `space-around` distributes space evenly around the items, meaning the first and last items have half the space of the inner gaps. `space-evenly` distributes space such that the spacing between any two adjacent items is equal, and the space before the first item and after the last item is also equal to the internal spacing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs