← Back to all snippets
CSS

Auto-Spacing Flex Items with Wrapping for Even Distribution

Master responsive layouts by distributing a variable number of flex items evenly across multiple lines using `justify-content: space-between` and `flex-wrap: wrap`.

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between; /* Distributes items with space between them */
  gap: 10px; /* Space between rows and columns */
  border: 1px solid #ccc;
  padding: 10px;
  width: 400px;
}

.item {
  flex: 0 0 auto; /* Prevent items from growing/shrinking, base on content */
  padding: 8px 15px;
  background-color: #e0f2f7;
  border: 1px solid #a7d9e8;
  border-radius: 5px;
  text-align: center;
  min-width: 80px; /* Ensure some minimum width */
}
How it works: This snippet demonstrates how to create a flexible container that automatically distributes a variable number of items, wrapping them onto new lines as needed. `justify-content: space-between` ensures items are spread out horizontally on each line, while `flex-wrap: wrap` handles the multi-line layout. `gap` provides consistent spacing between items. `flex: 0 0 auto` ensures items maintain their content-based size without growing or shrinking, adapting gracefully to different screen sizes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs