CSS

Responsive Image Gallery with Flexbox Wrapping

Build a flexible image gallery that responsively adjusts the number of items per row using CSS Flexbox, ensuring even spacing and wrapping for optimal display on any screen size.

/* HTML Structure Example: */
/*
<div class="gallery-container">
  <div class="gallery-item">Item 1</div>
  <div class="gallery-item">Item 2</div>
  <div class="gallery-item">Item 3</div>
  <div class="gallery-item">Item 4</div>
  <div class="gallery-item">Item 5</div>
  <div class="gallery-item">Item 6</div>
</div>
*/

.gallery-container {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5em; /* Spacing between items */
  justify-content: center; /* Center items when they don't fill a full row */
  padding: 1em;
}

.gallery-item {
  flex: 1 1 calc(33.333% - 1em); /* Approx 3 items per row, considering gap */
  min-width: 280px; /* Minimum width before wrapping */
  background-color: #f0f0f0;
  padding: 1em;
  border: 1px solid #ccc;
  box-sizing: border-box;
  text-align: center;
}
How it works: This snippet creates a responsive image gallery using Flexbox. The `gallery-container` uses `display: flex` and `flex-wrap: wrap` to allow items to flow to the next line. `gap` provides consistent spacing between items. Each `gallery-item` uses `flex: 1 1 calc(33.333% - 1em)` to make items grow, shrink, and take up approximately one-third of the available space, dynamically adjusting the number of items per row based on the container's width and the `min-width` property.

Need help integrating this into your project?

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

Hire DigitalCodeLabs