CSS

Flexbox Responsive Image Gallery with Dynamic Gaps

Create a responsive image gallery using Flexbox, where images wrap to new lines, maintain aspect ratio, and have consistent spacing with the `gap` property.

.image-gallery {
  display: flex;
  flex-wrap: wrap; /* Allows items to wrap to the next line */
  gap: 15px; /* Consistent spacing between items */
  padding: 20px;
  justify-content: center; /* Center items when there's extra space */
}

.gallery-item {
  flex: 1 1 auto; /* Allows items to grow, shrink, and have an initial auto basis */
  min-width: 250px; /* Minimum width for each image */
  max-width: 350px; /* Max width to prevent overly large images */
  box-sizing: border-box; /* Include padding/border in width calculation */
}

.gallery-item img {
  width: 100%;
  height: 200px; /* Fixed height for consistency, or use object-fit */
  object-fit: cover; /* Crops image to fit without distortion */
  display: block; /* Removes extra space below image */
  border-radius: 8px;
}
How it works: This snippet creates a responsive image gallery using Flexbox. The `.image-gallery` container uses `display: flex` and `flex-wrap: wrap` to allow images to flow onto new lines as needed. The `gap` property provides consistent spacing between all gallery items, regardless of whether they are on the same row or different rows. Each `.gallery-item` is given `flex: 1 1 auto` along with `min-width` and `max-width` to ensure they dynamically resize, grow to fill space, or shrink, while maintaining a pleasing layout. `object-fit: cover` on the images ensures they fill their containers without distortion, even with a fixed height.

Need help integrating this into your project?

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

Hire DigitalCodeLabs