I have a series of images that are written to the page with the following code.
<div class="gallery">
<div><img src="img1.jpg">stuff here</div>
<div><img src="img2.jpg">stuff here</div>
<div><img src="img3.jpg">stuff here</div>
....
</div>
Our design team want these images laid out in two columns. the number of images is variable, as is the height of each image. The layout they have requested is something similar to below. The idea is that each column is relatively equal in height - obviously won't be exact.
+------+ +------+
| | | |
| | | |
+------+ | |
+------+ | |
| | +------+
| | +------+
| | | |
| | | |
| | +------+
| | +------+
+------+ | |
+------+ | |
| | | |
~~~~~~~~ ~~~~~~~~
undefined height
CSS Flex nearly lays the images out as we need, but I cannot work out how to tell flex where to wrap the image list onto the second column. I cannot set the height of the container as individual image heights are variable. The amount of images will change over time although I can use PHP to calculate the number of images before the page is rendered.
An additional hurdle, is the layout is for mobile devices, but is different for larger screens (3 columns for tablet, 4 columns for desktop etc). so I can't just use 2 divs for columns. It has to be fluid.
What is the best way to achieve this? Is Flex even the right tool?
my code so far works, but I have manually set a height
<div class="gallery">
<div><img src="img1.jpg">stuff here</div>
<div><img src="img2.jpg">stuff here</div>
<div><img src="img3.jpg">stuff here</div>
<div><img src="img4.jpg">stuff here</div>
<div><img src="img5.jpg">stuff here</div>
<div><img src="img6.jpg">stuff here</div>
<div><img src="img7.jpg">stuff here</div>
<div><img src="img8.jpg">stuff here</div>
<div><img src="img9.jpg">stuff here</div>
</div>
<style>
.gallery {
display: flex;
flex-direction: column;
align-items: start;
height: 1200px;
flex-wrap: wrap;
}
.gallery > div {
width: 50%;
padding: 15px;
text-align: right;
position: relative;
}
img {
width: 100%;
height: auto;
}
</style>