Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

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

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

display: flex;
flex-flow: row-wrap;

and its children with:

flex: 1 0 10rem;

However, the LAST line will (depending on the amount of blocks in that line) have different widths for its boxes in comparison to the boxes in the previous lines. Is there a way to work around this while still using flex-grow?

HTML

<section>
    <div>aaaaaaaaaaaaaaaaaaaa</div>
    <div>bbbbbbbbbbbbbbbbbbbb</div>
    <div>cccccccccccccccccccc</div>
    <div>dddddddddddddddddddd</div>
    <div>eeeeeeeeeeeeeeeeeeee</div>
    <div>ffffffffffffffffffff</div>
    <div>gggggggggggggggggggg</div>
</section>

CSS

section {
    display: flex;
    flex-flow: row wrap;
    background-color: blue;
    width: 700px;
}

div {
    background-color: red;
    height: 100px;
    flex: 1 0 200px;
}

div:nth-child(even) {
    background-color: green;
}

Note in http://jsfiddle.net/C2q8D/3/ that the flex items in the last line are bigger than the lines above (as there are less items on that line to divide the space).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...