CSS

Evenly Distribute Items in a Row with Flexbox

Learn how to create a responsive group of elements that are evenly spaced and aligned across a container using various Flexbox distribution properties.

.button-group {
  display: flex;
  justify-content: space-around; /* Distributes items with space around them */
  /* Other options:
     justify-content: space-between; (First item to start, last to end, even space in between)
     justify-content: space-evenly;  (Even space between and on ends)
     justify-content: center;        (Group items in the center)
  */
  align-items: center; /* Aligns items vertically in the middle */
  gap: 10px;           /* Space between flex items (modern browsers) */
  padding: 15px;
  background-color: #e9ecef;
  border-radius: 5px;
}

.button-group .btn {
  flex: 0 0 auto; /* Prevent buttons from stretching or shrinking, maintain natural size */
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  font-size: 16px;
}

/* Optional: Responsive stacking for small screens */
@media (max-width: 600px) {
  .button-group {
    flex-direction: column; /* Stack buttons vertically */
    justify-content: flex-start; /* Align to start when stacked */
    align-items: stretch;     /* Make buttons full width */
  }
  .button-group .btn {
    width: 100%; /* Ensure full width when stacked */
  }
}
How it works: This snippet shows how to effectively distribute multiple items, such as buttons in a group, evenly within a container using Flexbox. `display: flex` makes the container a flex context. `justify-content: space-around` distributes items such that there is equal space around each item, including the first and last. Other `justify-content` values like `space-between` or `space-evenly` offer different distribution patterns. `align-items: center` ensures vertical alignment. `flex: 0 0 auto` on the items prevents them from stretching, maintaining their natural size. A media query demonstrates how to stack the buttons vertically on smaller screens.

Need help integrating this into your project?

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

Hire DigitalCodeLabs