With just a handful of CSS properties, we can create an intrinsically responsive photo gallery using flexbox. This is accomplished by setting our preferred width as the flex-basis
value and allowing items to both shrink and grow. The use of object-fit: cover
on images allows them to fully fill up the list item without distortion or overflow. We finish the gallery with a small animated effect that alters opacity
.
body { margin: 0.5rem; background-color: #222; } .gallery { list-style: none; padding: 0; margin: 0; display: flex; flex-wrap: wrap; } .gallery li { flex: 1 1 15rem; /*flex-grow and flex-shrink flex-baisis*/ min-height: 30vh; max-height: calc(50vh - 0.5rem); } img { object-fit: cover; width: 100%; height: 100%; opacity: 0.7; transition: 180ms opacity ease-in-out; } img:hover { opacity: 1; }
<iframe height="240" src="https://codesandbox.io/embed/eckles-flexbox-gallery-68rn0?fontsize=14&hidenavigation=1&theme=dark" style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden;" title="eckles-flexbox-gallery" width="320"></iframe>