CSS:不规则网格布局

6

我正在尝试使用CSS创建不规则网格布局。这是我的Jfiddle链接:

http://jsfiddle.net/F94gu/1/

代码:

HTML:

<div style="width:275px;">
     <div class="box" id="box1"></div>
     <div class="box" id="box2"></div>
     <div class="box" id="box4"></div>
     <div class="box" id="box5"></div>
     <div class="box" id="box3"></div>
     <div class="box" id="box6"></div>
</div>

CSS:

.box { margin: 2px; float:left; }
#box1 { height: 86px; width:  80px; background-color: red;}
#box2 { height: 42px; width:  161px; background-color: green;}
#box3 { height: 42px; width:  80px; background-color: blue;}
#box4 { height: 86px; width:  80px; background-color: orange;}
#box5 { height: 129px; width: 80px; background-color: yellow;}
#box6 { height: 42px; width:  161px; background-color: brown;}

我想要做的是将蓝色块向上移动(直接放在红色块下面),这样棕色块就可以向左上移动。下面是当前的样子和我想要的样子的对比图。

enter image description here

希望这些信息足够了解问题,如果需要更多信息我很乐意进行澄清。我知道像素有点不准确,它只有我所需大小的四分之一大小,因此我将所有像素定义除以4,这导致一些小数被忽略(并导致线条不能完美匹配)。


1
http://masonry.desandro.com/ - Pedro Estrada
我更喜欢用纯CSS的方法来实现这个,如果可能的话。不过,我还是很感谢提供的库,并且如果找不到更简单的方法的话,我会研究一下它。 - Jake
4个回答

2

http://jsfiddle.net/F94gu/2/

“肮脏”的解决方案,使用负边距,但是...”
  .box { margin: 2px; float:left; }

    #box1 { height: 86px; width:  80px; background-color: red;}
    #box2 { height: 42px; width:  161px; background-color: green;}
    #box3 { height: 42px; width:  80px; background-color: blue;margin-top:-87px;}
    #box4 { height: 86px; width:  80px; background-color: orange;}
    #box5 { height: 129px; width: 80px; background-color: yellow;}
    #box6 { height: 40px; width:  163px; background-color: brown;margin-top:-42px;}

这个解决方案之所以“肮脏”,是因为它很丑陋,还是因为它会导致某种兼容性问题或其他问题?总的来说,我认为它非常完美,它能够像应该做的那样工作。 - Jake
它并不肮脏,负边距并不邪恶。你的内容是静态的吗?这是最佳选择。 - enapupe
我的内容是文本,我将通过CSS/PHP进行样式化(并限制长度),因此尽管它实际上不是静态的,但它可能就像静态的一样。 - Jake

0

但是它会增加很多负担。无论如何,如果您的内容不是静态的并且无法手动编码,则是最佳解决方案。 - enapupe

-1

你应该为每个盒子设置绝对位置,然后使用左右定位。


-2

在我看来,这不是一个解决方案。为什么不在CSS中使用真正的网格指令呢?

如果您想要,甚至可以使其响应式。我已经做过很多次了,而且它可以跨浏览器工作。

https://grid.layoutit.com/


1
这个问题来自2014年,你发布的URL根据Wayback Machine的记录是在2019年出现的。CSS网格本身是在2017年左右实现的(https://alistapart.com/article/the-story-of-css-grid-from-its-creators/)。这就是你“为什么不”的答案 - 你已经挖掘了一个旧问题。 - Jake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接