CSS3 Multiple Columns

2019-09-02 19:10发布

问题:

I'm using CSS to create multiple columns, to give a similar kind of look to the Pinterest interface (e.g. columns of boxes, but neatly stacking underneath one another).

Here's the code I'm using:

#feed-post-home .feed {
    -moz-column-count:3; /* Firefox */
    -webkit-column-count:3; /* Safari and Chrome */
    column-count:3;
}

#feed-post-home .feed > section {
    margin-bottom: 10px;
}

#feed-post-home .feed > section > .content {
    background: #d4d4d4;
    padding: 10px;
}

As you can see in the image below, this almost works perfectly:

But on closer inspection, you can see some of the boxes are split in two, I've highlighted my problem in the next image, the orange rectangles show which boxes are supposed to be one, instead of being split in two:

Does anyone know what (if anything) I can add to my CSS to prevent elements being split up in this way? I'd rather they just stacked beneath one another as whole elements, even if the end result looks a little unbalanced

回答1:

As shown on the duplicated post, you need to do:

#feed-post-home .feed > section {
    margin-bottom: 10px;
    -webkit-column-break-inside: avoid;   /* Chrome webkit browsers */
    page-break-inside: avoid;             /* FF */
    break-inside: avoid-column;           /* Convention */ 
}

You could also set their display as inline-block to prevent the breaks.

#feed-post-home .feed > section {
    margin-bottom: 10px;
    display: inline-block;
}