Search code examples
cssresponsive-designcss-multicolumn-layout

CSS column layout has an incorrect column-count


I'm trying to make responsive layout with columns but in some cases their count is changing. I've set column-count:3 but when I have 4 divs they are positioned 2x2 not 3x1.

The same bug occurs when I have 7 columns and so on.

#content {
    width: 980px;
    height:1000px;
    position:relative;
    margin: 0 auto 0 auto;
    background-color:white;
    max-width: 980px;
}

#columns {
    font-size:1em;
    -webkit-column-count: 3;
    -webkit-column-gap: 0.625em;
    -webkit-column-fill: balance;
    -moz-column-count: 3;
    -moz-column-gap: 0.625em;
    -moz-column-fill: balance;
    column-count: 3;
    column-gap: 0.625em;
    column-fill: balance;
}

.news {
    margin-bottom:0.938em;
    display: inline-block;
    background: blue;
    -webkit-column-break-inside: avoid;
    -moz-column-break-inside: avoid;
    column-break-inside: avoid;
    padding: 0.625em;
}

.newsheader {
    width:100%;
    padding-bottom: 0.75em;
}
<div id="wrapper">
    <div id="content">
        <div id="columns">
            <div class="news">
                <p class="newsheader">Lorem ipsum dolor sit amet...</p> <span class="newscontent">Lorem ipsum dolor sit amet...</span>
            </div>
            <div class="news">
                <p class="newsheader">Lorem ipsum dolor sit amet...</p> <span class="newscontent">Lorem ipsum dolor sit amet...</span>
            </div>
            <div class="news">
                <p class="newsheader">Lorem ipsum dolor sit amet...</p> <span class="newscontent">Lorem ipsum dolor sit amet...</span>
            </div>
            <div class="news">
                <p class="newsheader">Lorem ipsum dolor sit amet...</p> <span class="newscontent">Lorem ipsum dolor sit amet...</span>
            </div>
        </div>
    </div>
</div>

Here's a JSFiddle demo: http://jsfiddle.net/BmG44/


Solution

  • Balancing columns

    Here's the behavior I observed in FF, Chrome, and Opera:

    1 element:    1 0 0
    2 elements:   1 1 0
    3 elements:   1 1 1
    
    4 elements:   2 2 0   (expected: 2 1 1)
    5 elements:   2 2 1
    6 elements:   2 2 2
    
    7 elements:   3 3 1   (expected: 3 2 2)
    8 elements:   3 3 2
    9 elements:   3 3 3
    

    With 4 and 7 elements, the browser is choosing to balance the first 2 columns, rather than spreading the elements out over as many columns as possible.

    Order of the elements

    The columns are filled sequentially when they're balanced. In other words, if 8 elements are added to 3 columns, the columns will be filled as shown below:

    1    4    7 
    2    5    8
    3    6
    

    ...rather than like this:

    1    2    3 
    4    5    6
    7    8
    

    Demo (tested in FF, Chrome, Opera)