Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to fill up empty spaces using Flex box

enter image description here

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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.

  1. change .flex-container { display: flex; } to: change .flex-container { display: grid; } to use CSS-Grid
  2. remove: .flex-container { height: 240px; flex-wrap: wrap; align-content: flex-start; } to remove unecessary flex-properties
  3. change .flex-item { width: 100px; }to: .flex-item { min-width: 100px; } which allows the elements to be widerr then 100px.
  4. 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading