Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make flexbox items with custom widths jump to available space

I'm trying to achieve Pinterest-like layout, but with items of different percentage widths. Expected behaviour is pretty much like Javascript masonry plugin.

My flexbox code for some reason does not nake flexbox items jump side-by-side to another, event, when exact space is available.

Illustration of what I'm trying to achieve Illustration of what I'm trying to achieve

demo on jsfiddle https://jsfiddle.net/31v7et9f/1/

html

<div class="masonry">
    <div class="item-1-4">item 25%</div>
    <div class="item-1-1">item 100%</div>
    <div class="item-3-4">item 75%</div>
    <div class="item-1-2">item 50%</div>
    <div class="item-1-2">item 50%</div>
    <div class="item-1-1">item 100%</div> 
</div>

css

* {box-sizing: border-box;}

/* parent */
.masonry {
    display: flex;
    flex-flow: column;
}

/* childs */
.masonry > div {
    background: gray;
    outline: solid 1px black;
    height: 100px;
}

/* child sizes */
.item-1-1 {width: 100%;}
.item-3-4 {width: 75%;}
.item-1-2 {width: 50%;}
.item-1-4 {width: 25%;}
like image 676
Dariusz Sikorski Avatar asked Jan 21 '26 06:01

Dariusz Sikorski


1 Answers

Flexbox items are by default layed out in the order they appear in the html. So, using your html and using flex-flow: row wrap; you'll get your 2 50%s side by side, but not your 75% and 25%.

/* parent */
 .masonry {
    display: -webkit-flex;
    display: flex;
    -webkit-flex-flow: row wrap;
    flex-flow: row wrap;
}

You could rearrange your html (do some math in javascript to determine which order they should be in to tile).

<div class="masonry">
    <div class="item-1-1">item 100%</div>
    <div class="item-1-4">item 25%</div>
    <div class="item-3-4">item 75%</div>
    <div class="item-1-2">item 50%</div>
    <div class="item-1-2">item 50%</div>
    <div class="item-1-1">item 100%</div> 
</div>

You could also use order to group items that should be able to tile, though it's not perfect

/* child sizes */
 .item-1-1 {
    width: 100%;
    -webkit-order: 1;
    order: 1;
}
.item-3-4 {
    width: 75%;
    -webkit-order: 2;
    order: 2;
}
.item-1-2 {
    width: 50%;
    -webkit-order: 3;
    order:3;
}
.item-1-4 {
    width: 25%;
    -webkit-order: 2;
    order:2;
}

https://jsfiddle.net/31v7et9f/2/

like image 170
Barbara Laird Avatar answered Jan 23 '26 20:01

Barbara Laird