0

I want to layout variable-height but fixed-width divs inside a fixed-width and variable-height container, so that the child divs look stacked on one another in a masonry kind of pattern, taking 2 or more columns.

Here's what I want:

enter image description here

And here's what I get with floats or FlexBox:

enter image description here

Here's the code pen: http://codepen.io/anon/pen/xOLwVJ

<div class="container">
  <div class="item">
  </div>
  <div class="item" style="height:250px;">
  </div>
  <div class="item" style="height:150px;">
  </div>
  <div class="item" style="height:200px;">
  </div>
  <div class="item" style="height:180px;">
  </div>
</div>

This code is only in reference to CodePen, not meant to represent the 2 images here.

Neither Flexbox nor Floats seem to work. The closest I have come to making it work is using columns, however they cut of child divs in the middle - it's ok for text, but not so for actual boxes.

I want HTML/CSS only solution with no JavaScript.

Fit Dev
  • 3,413
  • 3
  • 30
  • 54

2 Answers2

1

Turns out it is possible with CSS columns after all. The trick was to set display:inline-block on child elements to prevent child divs being cut in the middle on column wraps.

<div class="container">
  <div class="item">
  </div>
  <div class="item" style="height:250px;">
  </div>
  <div class="item" style="height:150px;">
  </div>
  <div class="item" style="height:200px;">
  </div>
  <div class="item" style="height:180px;">
  </div>
</div>

And the CSS:

.container {
  margin: 0 auto;
  width:600px;
  background:#ddd;
  display: block;
  -webkit-column-count: 2;
  -moz-column-count: 2;
  column-count: 2;
}
  .item {
    margin:10px;
    background:red;
    width:270px;
    height:100px;
    display:inline-block; /* this is to prevent div being cut in the middle when it flows onto the next column */
  }

Codepen: http://codepen.io/anon/pen/GqvoBO

Fit Dev
  • 3,413
  • 3
  • 30
  • 54
0

this is jsfiddle for your question i hope this is useful for you (https://jsfiddle.net/ahe128/anhw21rj/)

<div id="main">
<div id="coloumn1">
  <div id="row1_1">
  </div>
   <div id="row1_2">
  </div>
    <div id="row1_3">
  </div>
</div>
<div id=coloumn2>
 <div id="row2_1">
  </div>
   <div id="row2_2">
  </div>
</div>
</div>

#main{
  height:500px;
  width:500px;
  border:1px solid black;
  margin:10px;
}
#coloumn1{
  height:400px;
  width:200px;
  float:left;
margin:10px;
   border:2px solid black;
}
#row1_1{
  height:150px;
  width:150px;
   border:1px solid black;
   margin:10px;
}
#row1_2{
  height:100px;
  width:150px;
margin:10px;
 border:1px solid black;
}
#row1_3{
  height:50px;
  width:150px;
margin:10px;
 border:1px solid black;
}
#coloumn2{
  height:400px;
  width:200px;
  float:left;
   border:2px solid black;
   margin:10px;
}
#row2_1{
  height:200px;
  width:150px;
   border:1px solid black;
   margin:10px;
}
#row2_2{
  height:150px;
  width:150px;
margin:10px;
 border:1px solid black;
}
ahe
  • 21
  • 4