Search code examples
csscss-multicolumn-layout

How to create variable columns and fill them up?


I have a list of items I'd like to have in columns next to each other. I don't know how many items there will be so I can't have a fixed height. I want them to fill the space a good as possible like so:

#parent {
  background-color: firebrick;
  max-height: 200px; /* <-- eliminate */
  display: flex;
  flex-flow: column wrap;
}

.child {
  background-color: #fff;
  height: 30px;
  width: 100px;
  margin: 10px;
  padding: 3px;
}
<div id="parent">
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
</div>

So I basically want the above but without the max-height on #parent but when I remove it they will just be in one wide column.


Solution

  • columns can do this:

    #parent {
      background-color: firebrick;
      column-width:120px; /* set the width of columns and the number will be automatic */
      column-gap: 20px; /* to replace margin between element */
      padding:0 10px;
    }
    
    .child {
      background-color: #fff;
      height: 30px;
      display:inline-block; /* use inline-block because block element are buggy */
      width:100%; /* make them full width so they behave like block */
      margin:10px 0; /* keep only top and bottom margin */
      padding: 3px;
      box-sizing:border-box;
    }
    <div id="parent">
      <div class="child">child</div>
      <div class="child">child</div>
      <div class="child">child</div>
      <div class="child">child</div>
      <div class="child">child</div>
      <div class="child">child</div>
      <div class="child">child</div>
      <div class="child">child</div>
    </div>