一个CSS俄罗斯方块风格的拼图

时间:2015-11-19 11:27:11

标签: javascript html css css3 layout

CLICK FOR PLAYGROUND

CHALLENGE

使用 CSS 创建一个没有任何空格的双列div布局。

开始布局

每个方框只是:<div class=A1">A1</div>

enter image description here

希望布局

enter image description here

简单吧?

有条件:

  1. 每个div的高度都是可变的。
  2. div的数量是可变的。
  3. 左右列的高度应尽可能相等。 (留下最小量的尾随空格)。
  4. 允许更改HTML
  5. div不需要按顺序显示。
  6. JavaScript解决方案是可以接受的,但获胜者将是能够使用纯CSS执行此操作的天才。

    注意: div实际上是使用.NET转发器生成的,但这不会对解决方案产生影响。

    更新

    使用Paran0a所指出的flex模型我已经到了这个阶段,使用一个小小的脚本来计算.Wrap的高度。然而,由于最后一个框可能很大,因此很难计算宽度的一半

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

    DEMO UPDATE

1 个答案:

答案 0 :(得分:2)

您能否支持flex-box

这是一个小小的演示。

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

&#13;
&#13;
$(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);
});
});
&#13;
.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;}
&#13;
<div class="Wrap"></div>
&#13;
&#13;
&#13;