22

I'm trying to balance the height between the columns in an image gallery I've made with the following code:

section {
    background: magenta;
    /* So you can see the area I don't want to appear */
}

.gallery {
    width: 100%;
    line-height: 0;
    -webkit-column-count: 2;
    -webkit-column-gap: 0;
    -moz-column-count: 2;
    -moz-column-gap: 0;
    column-count: 2;
    column-gap: 0;
}
<section class="gallery">
    <div>
        <img src="http://lorempixel.com/800/1000/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/600/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/200/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/700/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/900/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/400/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/200/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/600/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/700/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/600/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/550/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/700/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/600/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/1000/">
    </div>
    <div>
        <img src="http://lorempixel.com/800/700/">
    </div>
</section>

Here's a JSFiddle: https://jsfiddle.net/auan2xnj/1/

The images all have different heights but all have the same width. My column-fill is set to balance (as by default).

The problem:

In the JSFiddle, it looks pretty good, but on the website I'm developing, some enormous gaps have appeared comparing the height of the columns. I'm guessing this is because of the orders the images have in the HTML, considering that's the exact same order they'll be put in the columns by the CSS. This is a screenshot from my project, using exactly the same code from the JSFiddle:

enter image description here

Behaviour:

When I give the .gallery element a hardcoded height value, the columns always balance much better. This is a problem because in my website, images are added dynamically and I'm never going to know the exact height of all the galleries.

Request:

I would like to find a piece of code (whatever it is, I think I can implement some JS) that fixes this issue, either by reordering the images in the HTML so that the outcome is the best possible, or whatever way there is in order to set a height dynamically so that the problem is solved.

6
  • Is overflow acceptable?
    – Bonatti
    Commented Jan 11, 2016 at 19:14
  • Do you mean overflow in the Y axis? As in, letting some of the images not show or be cropped? In that case, no, all the images need to be shown.
    – fnune
    Commented Jan 11, 2016 at 19:15
  • The main issue I see with your provided code is that the columns are uneven. That is, you have two columns, but provide 15 images. Adding a 16th image makes the gap much smaller (almost completely gone in some cases) jsfiddle.net/auan2xnj/4 Commented Jan 11, 2016 at 19:36
  • 2
    @GlenDespaux That the images can't be divided into an even number of images or an even number of pixels in height isn't the problem. In his JPEG he has a very tall image at the bottom of the first column causing confusion, but in the jfiddle you see the first column being several images taller than the second, not just one or two. The column-fill algorithm itself sucks right now. Hopefully they'll improve it.
    – Lee Saxon
    Commented Jan 11, 2016 at 19:50
  • @JosephLeeSaxon I found out that the "column fill algorithm", just take the equal amounts of elements into the columns. I dont think they will changes this.
    – CoderPi
    Commented Jan 11, 2016 at 19:52

5 Answers 5

9
+50

EDIT: If you don't need to keep line-height: 0 you would simply use .gallery img {display:block} and remove line-height, it's all you need. That would be the best. table-cell and so on can have some side-effects. For example vertical-align: middle leave a space under the images, and is just a hack.

https://jsfiddle.net/bruLwktv/


Challange accepted, here is the solution: ;)

The algorithm makes sure every images is loaded and then partition them into both coloumns in a way the have about the closest total height possible to create a minimal gap.

Using The greedy algorithm for the Partition problem to create Balanced partitions.

var gallery = document.getElementsByClassName("gallery")[0]
var images = gallery.getElementsByTagName("img")
var notLoaded = 0

window.onload = function() {
  for (var i = images.length; i--;) {
    if (images[i].width == 0) {
      // let the image tell us when its loaded
      notLoaded++
      images[i].onload = function() {
        if (--notLoaded == 0) {
          allImgLoaded()
        }
      }
    }
  }
  // check if all images are already loaded
  if (notLoaded == 0) allImgLoaded()
}

function allImgLoaded() {
  // Partition images
  var imgs = partitionImages(images)
  // reorder DOM
  for (var i = images.length; i--;) {
    gallery.appendChild(imgs[i])
  }
}

function partitionImages(images) {
  var groupA = [], totalA = 0
  var groupB = [], totalB = 0

  // new array width img and height
  var imgs = []
  for (var i = images.length; i--;) {
    imgs.push([images[i], images[i].height])
  }
  // sort asc
  imgs.sort(function(a, b) {
    return b[1] - a[1]
  });
  // reverse loop
  for (var i = imgs.length; i--;) {
    if (totalA < totalB) {
      groupA.push(imgs[i][0])
      totalA += imgs[i][1]
    } else {
      groupB.push(imgs[i][0])
      totalB += imgs[i][1]
    }
  }

  return groupA.concat(groupB)
}
section {
  background: magenta;
  /* So you can see the area I don't want to appear */
}
.gallery {
  width: 100%;
  line-height: 0;
  -webkit-column-count: 2;
  -webkit-column-gap: 0;
  -moz-column-count: 2;
  -moz-column-gap: 0;
  column-count: 2;
  column-gap: 0;
}
<section class="gallery">
  <div><img src="http://lorempixel.com/800/1000/"></div>
  <div><img src="http://lorempixel.com/800/600/"></div>
  <div><img src="http://lorempixel.com/800/200/"></div>
  <div><img src="http://lorempixel.com/800/700/"></div>
  <div><img src="http://lorempixel.com/800/900/"></div>
  <div><img src="http://lorempixel.com/800/400/"></div>
  <div><img src="http://lorempixel.com/800/200/"></div>
  <div><img src="http://lorempixel.com/800/600/"></div>
  <div><img src="http://lorempixel.com/800/700/"></div>
  <div><img src="http://lorempixel.com/800/600/"></div>
  <div><img src="http://lorempixel.com/800/550/"></div>
  <div><img src="http://lorempixel.com/800/700/"></div>
  <div><img src="http://lorempixel.com/800/600/"></div>
  <div><img src="http://lorempixel.com/800/1000/"></div>
  <div><img src="http://lorempixel.com/800/700/"></div>
</section>

10
  • This is a good solution. Not sure if it's "the best" one to be had, but definitely nifty - making sure that you add each additional image to the shorter of the two columns. I like it!
    – Tricky12
    Commented Jan 11, 2016 at 19:55
  • Very interesting idea if you don't have a particular order you need your images / elements to appear in - but I would think most of the time you would. If so, my solution tends to minimize the gap as well, though in a less powerful way.
    – Lee Saxon
    Commented Jan 11, 2016 at 20:00
  • @FaustoNA I could also add a little cropping on top and bottom of each image of the bigger coloumn to make both coloums equal if you want? This will provid minimal area loss on the images while having 0 gaps
    – CoderPi
    Commented Jan 11, 2016 at 20:05
  • @CodeiSir How would you go about the cropping? That would be pretty nice.
    – fnune
    Commented Jan 11, 2016 at 20:14
  • 1
    @FaustoNA I gave it a go here - jsfiddle.net/auan2xnj/6. However, you may be able to get a better working version than mine. I added a comment to the javascript I added.
    – Tricky12
    Commented Jan 11, 2016 at 21:20
3

Yeah, column implementation is bizarre right now.

If you get rid of "line-height: 0;" this problem becomes much less severe. I have no idea why. Except to say that the line-height thing is a hack to get rid of that omnipresent little space/margin at the bottom of images (remove the line-spacing rule in the jfiddle if you don't know what I'm talking about).

Supposedly that space/margin is there because HTML doesn't know an img element isn't text and so leaves room for the "tails" of characters like "y" and "g" which go below the line. This is a ridiculous bug which I think should've been fixed a decade ago. To me, this is up there with IE<9 levels of stupid implementation.

Anyway, rant over, a way to fix that space/margin without using the line-height hack:

img {
    vertical-align: middle;
}

Also, it's not an issue if you're positive all your images will be the same width, but in the fiddle the gap problem is made worse by images overlapping the widths of the columns. You should set

img {
    width: 100%
    // and, for insurance, I also add:
    height: auto;
}

to make sure you're fitting the images into the columns.

9
  • can you add a JSFiddle so I can try it?
    – CoderPi
    Commented Jan 11, 2016 at 20:04
  • This works flawlessly. And though your answer @CodeiSir is more elaborate, I think this solves the problem more elegantly. Here's a JSFiddle: jsfiddle.net/auan2xnj/5
    – fnune
    Commented Jan 11, 2016 at 20:05
  • Do keep in mind however as I mentioned on his answer that if you don't need the images in a certain order his way is potentially more powerful. If you've got one particularly tall image in a certain place (as in the JPEG you provided in the original answer), for example, you might need to look to his solution.
    – Lee Saxon
    Commented Jan 11, 2016 at 20:08
  • @FaustoNA the fiddle has not diffrence with or without the vertical-align: middle;. It's already sorted. What did I miss?
    – CoderPi
    Commented Jan 11, 2016 at 20:11
  • Yes, I'm accepting his answer for the effort and for the potential of his code. But it's a tough one! Thanks guys.
    – fnune
    Commented Jan 11, 2016 at 20:11
1

I've added some CSS to the <div> elements, let me know if this works:

https://jsfiddle.net/rplittle/auan2xnj/3/

I've also seen this:

div {
  -webkit-margin-before: 0;
  -webkit-margin-after: 0;
}

(adjust/add prefixes if necessary)

Or you could try Masonry, it's well-built and pretty easy to set up.

4
  • Thanks but that doesn't seem to have solved it for me neither in the JSFiddle nor in my project (should be the same effect). I see a small change in the position of some of the images, but the gap is pretty much the same.
    – fnune
    Commented Jan 11, 2016 at 19:29
  • Edited my answer to suggest a library
    – RPL
    Commented Jan 11, 2016 at 19:32
  • What browser are you using? I don't see any spacing in mine (Chrome 47 / Mac 10.11.2)
    – RPL
    Commented Jan 11, 2016 at 19:36
  • @RyanLittle On up-to-date Chrome 47 on Windows 7 I see no change to the gap with your version. Not sure why you'd be getting a different calculation. Also, adding "width: 100%" to DIV won't keep the images from overflowing the columns, you have to add it to IMG.
    – Lee Saxon
    Commented Jan 11, 2016 at 19:47
1

Request:

I would like to find a piece of code (whatever it is, I think I can implement >> some JS) that fixes this issue, either by reordering the images in the HTML so >> that the outcome is the best possible, or whatever way there is in order to set a height dynamically so that the problem is solved.

the greedy algorithm is a nice approach, and useful for streams, where you have to dynamically extend the tiles. (like pagination)

I've included a function that does a better balancing by grouping the items and switching items between the groups.

The columns here are implemented by creating 2 divs that are inline-block and 50% width; simple and works across all modern browsers.

function balance(numGroups, items, fetchValue){
    function delta(a, b){
        var da = a-avg, db = b-avg;
        return da*da + db*db;
    }

    function testAndSwitchItems(a,b){
        var valueA, valueB,
            lengthA = a.length, lengthB = b.length,
            indexA = lengthA, indexB = lengthB,
            bestDelta = delta(a.sum, b.sum);

        //test every item in this first column against every value in the second column
        for(var i = 0; i <= lengthA; ++i){
            //accessing a not available index of an Array may deoptimize this function
            //that's why i check the index before accessing the element.
            valueA = (i < lengthA && a[i] || nullElement).value;

            for(var j = 0; j <= lengthB; ++j){
                valueB = (j < lengthB && b[j] || nullElement).value;

                //test wether it would be an improvement to switch these items
                var d = delta(
                    a.sum + valueB - valueA, 
                    b.sum + valueA - valueB
                );

                //find the best combination
                if(d < bestDelta){
                    indexA = i;
                    indexB = j;
                    bestDelta = d;
                }
            }
        }


        var elmA = indexA < lengthA && a[indexA], 
            elmB = indexB < lengthB && b[indexB],
            tmp;

        if(elmA && elmB){
            //switch items
            a[indexA] = elmB;
            b[indexB] = elmA;

        }else if(elmA){
            //move an item from a to b
            b.push(elmA);
            tmp = a.pop()
            if(elmA !== tmp)
                a[indexA] = tmp;

        }else if(elmB){
            //move an item from b to a
            a.push(elmB);
            tmp = b.pop()
            if(elmB !== tmp)
                b[indexB] = tmp;

        }else{
            //no switch would improve the result
            return false;
        }

        //compute the new sums per group
        valueA = (elmA || nullElement).value;
        valueB = (elmB || nullElement).value;
        a.sum += valueB - valueA;
        b.sum += valueA - valueB;
        return true;
    }

    function initGroupsAndReturnSum(sum, item, i){
        var value = fetchValue? fetchValue(item): item;

        //distribute the items
        if(i<numGroups){
            var group = groups[i] = [];
            group.sum = value;
        }else{
            group = groups[ i%numGroups ];
            group.sum += value;
        }

        group.push({
            index: i,
            value: value
        });

        return sum + value;
    }

    var groups = [],
        nullElement = { value: 0 },
        //don't care wether items is an Array, a nodeList or a jQuery-object/list, ...
        avg = groups.reduce.call(items, initGroupsAndReturnSum, 0) / groups.length;

    //start switching items between the groups
    do {
        for(var i=1, done = true; i<groups.length; ++i)
            for(var j=0; j<i; ++j)
                //test each combination of groups
                if(testAndSwitchItems(groups[j], groups[i])){
                    //this switch may have affected the computation against other groups
                    //do another loop
                    done = false;
                }
    }while(!done);

    function sorter(a,b){
        return a.index - b.index
    }

    function getItem(item){
        return items[item.index]
    }

    return groups.map(function(a){ 
        return a.sort(sorter).map(getItem) 
    });
}

and a possible way to use it

var groups = balance(2, //num columns
        //something Arraylike that contains some objects to be grouped
        document.querySelectorAll('img'),
        //a function to compute a value out of an Array-item
        img => img.naturalHeight / img.naturalWidth
    );

https://jsfiddle.net/77o3ptk2/2/

Just for the sake of it, the example also includes a few more styles like a padding around the images and an enumeration, to show how much the array has been shuffled.

0
0

You can equalize height of each column using this http://brm.io/jquery-match-height/ . And its also good in mobile responsive. No need for css, just add the library and put this snippet

$(function() {
    $('.gallery').find('div').matchHeight(options);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.