DreamTeK
DreamTeK

Reputation: 34177

A CSS Tetris style puzzle

CLICK FOR PLAYGROUND


CHALLENGE

Create a two column div layout without any spaces using CSS.

STARTING LAYOUT

Where each box is simply: <div class=A1">A1</div>

enter image description here

DESIRED LAYOUT

enter image description here


Simple right?

Well there are conditions:

  1. The heights of each div are variable.
  2. The number of divs is variable.
  3. The height of left and right column should be as equal as possible. (Leaving a minimum amount of trailing white space).
  4. Changing the HTML is allowed.
  5. The divs do not need to display in order.

JavaScript solutions are acceptable but the winner will be the genius who can do this with pure CSS.

NOTE: The divs are actually generated using a .NET repeater but this should not impact on the solution.


UPDATE

Using flex model as noted by Paran0a I have got to this stage using a tiny script to calculate the height of .Wrap However it's hard to calculate half the width correclty as the last box could be huge.

var h = 0;
$('.Wrap > div').each(function() {
    $(this).height(Math.random()*100);        
    h += $(this).height();        
});
$('.Wrap').height((h/2));

DEMO UPDATE

Upvotes: 0

Views: 609

Answers (1)

Paran0a
Paran0a

Reputation: 3447

Would you be able to support flex-box?

Here's a little demo.

http://jsfiddle.net/oLzw742p/3/

$(function(){
var test = [],
    num = 1,
   		randomNo = Math.floor(Math.random() * 8) + 2;
for (i = 1; i <= randomNo; i++) {
    test[i] = $('.Wrap').append('<div class="A'+(i)+'">A'+(i)+'</div>');
};
$('.Wrap > div').each(function() {
    $(this).height(Math.random()*100);
});
});
.Wrap {
  display: flex;
  width: 500px;
  height: 400px;
  background: #E0E0E0;
  flex-direction: column;
  flex-flow: column wrap;
}

.Wrap > div {
  font-family: sans-serif;
  font-size: 20px;
  width: 200px;
  box-sizing: border-box;
  background: orange;
  padding: 10px;
  box-sizing: border-box;
  margin: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.Wrap div:nth-child(5n+1) {background: blue;}
.Wrap div:nth-child(5n+2) {background: red;}
.Wrap div:nth-child(5n+3) {background: green;}
.Wrap div:nth-child(5n+4) {background: purple;}
.Wrap div:nth-child(5n+5) {background: black;}
<div class="Wrap"></div>

Upvotes: 2

Related Questions