Managing CSS flex-box growth in multi-line to create a grid of equal blocks

前端 未结 2 742
礼貌的吻别
礼貌的吻别 2020-12-20 17:51

I am looking for a way to create equally sized boxes with flexbox while using flex-growth: 1. This works pretty good by defining t

相关标签:
2条回答
  • 2020-12-20 18:17

    Seems like if flex-grow is set to 1, you have explicitly declared that you don't care for the boxes to be equally sized — when a given line has fewer items, you have instructed it to grow larger than your flex-basis.

    Does setting a max-width on items equal to your flex-basis achieve what you want? See http://jsfiddle.net/C2q8D/4/ for that. I added a justify-content property to the flex container as well; just experimenting myself with how it affects this layout.

    0 讨论(0)
  • 2020-12-20 18:27

    This is totally possible, however, you have to know how many columns you'll have at a maximum. http://jsfiddle.net/kelunik/C2q8D/6/

    Solution

    By adding a few empty placeholders, your cards get equally sized. You just have to make sure, you're adding enough placeholders. It doesn't matter if there are too many, because they'll have a height of zero and are not visible.

    CSS

    section {
        display: flex;
        flex-flow: row wrap;
        background-color: blue;
    }
    
    div {
        background-color: red;
        height: 3rem;
        flex: 1 0 10rem;
    }
    
    div:nth-child(even) {
        background-color: green;
    }
    
    div:empty {
        margin: 0;
        height: 0;
        border: 0;
        background: transparent;
    }
    

    HTML

    <section>
        <div>a</div>
        <div>b</div>
        <div>c</div>
        <div>d</div>
        <div>e</div>
        <div>f</div>
        <div>g</div>
        <div>h</div>
        <div>i</div>
        <div>j</div>
        <div>k</div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </section>
    
    0 讨论(0)
提交回复
热议问题