如何将div / snap / fit div包装成网格布局,TETRIS样式?

时间:2014-09-26 19:48:24

标签: html css

我很难用语言解释我在寻找什么,所以这是一个例子:

http://jsfiddle.net/toaeb0zt/

<div style="width:800px ">
<div style="width:200px;height:500px; background:purple; float:left"></div>
<div style="width:200px;height:200px; background:blue; float:left"></div>
<div style="width:200px;height:200px; background:green; float:left"></div>
<div style="width:200px;height:400px; background:yellow; float:right"></div>
<div style="width:400px;height:200px; background:orange; float:left"></div>
<div style="width:200px;height:200px; background:brown; float:left"></div>
<div style="width:400px;height:200px; background:gray; float:left"></div>
<div style="width:200px;height:100px; background:red; float:left;"></div>
</div>

这种布局是通过结合左右浮动的CSS完成的。我读到了关于flexbox的信息,看它是否可以做到,但看起来这是负面的。

我意识到可以通过将div嵌套到更大的div来完成,但我需要做出响应,这个解决方案会让响应成为一场噩梦。

我一直试图远离jQuery和更深入的编程,但我知道它可能是最好的选择。我很感谢这个社区的帮助;提前谢谢你。

2 个答案:

答案 0 :(得分:1)

你在做什么在我看来就像一场噩梦!有很多lib可以帮助你将这个网格组合在一起。砌体网格将与您的要求最符合。

砌筑的工作原理是根据可用的垂直空间将元素放置在最佳位置,有点像石膏在墙上贴合石头。你可能已经看到它在互联网上使用。

我使用了Isotope很多!这是你可以用同位素做的很多事情之一: http://codepen.io/desandro/pen/mEinp

$( function() {

  $('.isotope').isotope({
    layoutMode: 'fitColumns',
    itemSelector: '.item'
  });
});

非常仔细地研究网站

http://isotope.metafizzy.co/

希望这会有所帮助/此解决方案需要JavaScript(和jQuery)

答案 1 :(得分:0)

您可以使用块表并为每个块着色。你可以使用css和一个简单的表来完成这个。

这是一个小提琴,http://jsfiddle.net/r3vycfa1/

我对你所寻找的不是肯定的,但这会更敏感。

类.a,.b,.c每个都有不同的颜色,您可以将它们应用到块中。

HTML

<table>
    <tr>
        <td class="a">&nbsp;</td>
        <td class="a">&nbsp;</td>
        <td class="b">&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td class="a">&nbsp;</td>
        <td>&nbsp;</td>
        <td class="b">&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td class="b">&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td class="c">&nbsp;</td>
        <td class="c">&nbsp;</td>
        <td class="c">&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>

CSS:

* {
    margin: 0;
    padding: 0;
}
table {
    width: 500px;
    height: 500px;
    border-spacing: 0px;
}
td {
    width: 10%;
    height: 10%;
}
.a {
    background-color: #00FF00;
}
.b {
    background-color: #FF0000;
}
.c {
    background-color: #0000FF;
}