CSS

Create a Responsive Item Wrap with Flexbox and Gap

Implement a flexible and responsive layout where items wrap to new lines, maintaining consistent spacing using Flexbox `flex-wrap` and `gap` properties.

.wrapper {
  display: flex;
  flex-wrap: wrap; /* Allows items to wrap onto multiple lines */
  gap: 20px; /* Space between flex items, both row and column */
  padding: 20px;
  background-color: #f8f8f8;
  border: 1px solid #eee;
}

.card {
  flex: 1 1 200px; /* Grow, shrink, base width */
  min-width: 180px; /* Ensures items don't get too small */
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 15px;
  text-align: center;
  font-family: sans-serif;
}

<div class="wrapper">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
  <div class="card">Card 4</div>
  <div class="card">Card 5</div>
  <div class="card">Card 6</div>
</div>
How it works: This snippet creates a responsive grid-like layout using Flexbox. By setting `display: flex` and `flex-wrap: wrap` on the container, items automatically flow to the next line if there's not enough space. The `gap` property provides consistent spacing between all items, horizontally and vertically, simplifying layout. Each `.card` uses `flex: 1 1 200px` to allow flexible growing and shrinking while aiming for a base width, making the layout adaptive to various 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