Is it possible to make this yellow square floats naturally to the empty grey square and so on?
Each flex-item represents a component they can use 50% or 100% of the container width, but i just have this information when im rendering it.
I was considering use only flexbox, but i dont know if it is possible.
.flex-container {
display: flex;
width: 200px;
height: 240px;
background: grey;
flex-wrap: wrap;
align-content: flex-start;
}
.flex-item {
width: 100px;
height: 100px;
}
.red {
background: red;
}
.blue {
background: blue;
width: 200px;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
<div class="container">
<div class="flex-container">
<div class="flex-item red"></div>
<div class="flex-item blue"></div>
<div class="flex-item yellow"></div>
<div class="flex-item green"></div>
</div>
</div>
>Solution :
With CSS-Grid it is possible by using the grid-auto-flow property: grid-auto-flow: row dense;
That will place items as dense as possible and automatically re-order them.
- change
.flex-container { display: flex; }to: change.flex-container { display: grid; }to use CSS-Grid - remove:
.flex-container { height: 240px; flex-wrap: wrap; align-content: flex-start; }to remove unecessary flex-properties - change
.flex-item { width: 100px; }to:.flex-item { min-width: 100px; }which allows the elements to be widerr then 100px. - change
.blue { width: 200px; }to:.blue { grid-column: span 2; }to have that element twice the width.
.flex-container {
display: grid;
width: 200px;
background: grey;
grid-auto-flow: row dense;
}
.flex-item {
min-width: 100px;
height: 100px;
}
.red {
background: red;
}
.blue {
background: blue;
grid-column: span 2;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
<div class="container">
<div class="flex-container">
<div class="flex-item red"></div>
<div class="flex-item blue"></div>
<div class="flex-item yellow"></div>
<div class="flex-item green"></div>
</div>
</div>
