I am looking to build out a simple version of Masonry layout for an image gallery I am building. I wanted to use flexbox and utilize flex-direction columns and row wrap to create most of the layout.
The biggest feature I want to implement is customers are going to be able to set how many columns they want for the image gallery.
I want to calculate how tall the container will be with JavaScript so that when they select a different option such as 25%, 33% or 50% it will create the layout. I have a fairly simple version working but I want the gallery to be as symmetrical as possible. What I am doing now is finding the width of all of the images and then adding those together. Then I divide that number by the desired number of columns and then add that height to the masonry-container. Is this the best way to be finding how tall the container should be?
(function() {
var width = 0;
var curr_height = 0;
var max_height = 0;
$('.image-wrapper img').each(function() {
width += $(this).width();
curr_height = $(this).height();
if (curr_height > max_height) {
max_height = curr_height;
}
});
var cols = 33.3333
console.log(width, 'im the width')
console.log(cols, 'im the num cols')
console.log(max_height, 'im the max height')
var containerHeight = (width * (cols / 100) - curr_height);
console.log(containerHeight);
$('.masonry-container').css('height', containerHeight);
})();
I created a JSFiddle here. https://jsfiddle.net/Lzyg5mos/2/