Home>

I want to create a layout that is packed with items of different heights, such as images.

Currently, the display looks like the image below. The whole is a flex container, with row direction + wrap wrapping and align-items: flex-start.

By applying align-items: flex-start, the height of each item itself can be made different, but I do not know how to further align the items vertically from here. Specifically, the white margin above the item in the lower left? I want to pack items, and I want to be able to handle more items with different heights in the future.

It doesn't matter if you play with HTML/CSS, but what changes can you make to make such a layout? Is such a layout possible with flexbox in the first place?

<ul>
<li>
     
     heading 
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis molestiae, neque expedita fugit voluptatum iusto aperiam deserunt impedit, quod a dolorum minima obcaecati quam excepturi earum sint at dolor hic!</P>
</li>
  <li>
     
     heading 
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis molestiae, neque expedita fugit voluptatum iusto aperiam deserunt impedit, quod a dolorum minima obcaecati quam excepturi earum sint at dolor hic!</P>
</li>
<li>
     
     heading 
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis molestiae, neque expedita fugit voluptatum iusto aperiam deserunt impedit, quod a dolorum minima obcaecati quam excepturi earum sint at dolor hic!</P>
</li>
<li>
     
     heading 
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis molestiae, neque expedita fugit voluptatum iusto aperiam deserunt impedit, quod a dolorum minima obcaecati quam excepturi earum sint at dolor hic!</P>
</li>
</ul>
* {box-sizing: border-box;margin: 0;padding: 0;list-style: none;}
.list {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: space-between;
}
.item {
  width: calc ((100% -16px)/2);
 /* debug * /
  border: 1px solid rgba (0,0,0, .4);
  background-color: rgba (0,0,0, .2);
}
.item-image {
  padding-top: 30%;
 /* debug * /
  border: 1px solid rgba (255,0,0, .4);
  background-color: rgba (255,0,0, .1);
}
.item-image-large {
  padding-top: 80%;
}
.item-heading {
  font-size: 2em;
}
  • Answer # 1

    Perhaps using grid instead of flexbox fits the questioner's wishes.

    Please refer to the following site to make it.
    CSS grid layout
    There is also a site called "Griddy" that allows you to easily generate CSS grid layout code.

  • Answer # 2

    If the number of columns may change or the number of elements may increase or decrease depending on the screen width,
    You may want to try specifying column-count instead of flexbox.

    https://coliss.com/articles/build-websites/operation/css/css-seamless-responsive-photo-grid-by-css-tricks.html

    If you can use javascript, try using Masonry.
    https://masonry.desandro.com/