Search code examples
csscss-multicolumn-layout

CSS column-count not respected


There's a similar question here with no real answer: CSS columns bug — 5 column count only showing 4 (with images)

I'm using column-count to display elements in columns (in this case a set of section elements but this happens regardless of the element used (obviously)).

The problem is that Chrome and Firefox (haven't tried others) don't always respect the specified column count.

If I set it to 4, sometimes it will be 4 and sometimes it will be less than 4 (never more, thankfully).

If I use Firebug (or similar) to modify the height of some of the elements in the columns sometimes the columns jump around from 3 to 4.

This is really strange and really annoying and I'm hoping someone knows why this happens and hopefully how to fix it.

div {
    -moz-column-count: 4;
    -webkit-column-count: 4;
    column-count: 4;
}
div img {
    display: block;
    margin: 0 0 10px;
}
<div>
    <img src="http://placehold.it/80x80">
    <img src="http://placehold.it/80x80">
    <img src="http://placehold.it/80x80">
    <img src="http://placehold.it/80x80">
    <img src="http://placehold.it/80x80">
</div>

Here's a JSFiddle displaying the problem: http://jsfiddle.net/NY2Zx/ you can play around with the dimensions of the images to see the column count change.


Solution

  • In your example (jsfiddle), there are 5 elements of equal size to be distributed into 4 columns. Since they won't fit next to each other (they are more than 4) , the first column will contain 2 elements. That defines the height of the container, so the second column will also get 2 elements, and so there's one remaining for the third column and none for the fourth column. There are four columns, but the fourth one is simply empty...

    In other words: The height of the container is determined by the minimum height which is needed to fit all elements into the number of columns. Once that is done, the content will be filled into the columns starting from the left, and each column will get as much content as fits into it.