没有定义列的纯CSS砌体布局 [英] Pure CSS Masonry Layout without defined columns
问题描述
我写了一个如上所述的布局.我使用宽度和高度不同的display: inline-block
和article
元素的简单用法实现了这一点,例如:
I wrote a layout as depicted above. I implemented this with the simple usage of display: inline-block
and article
elements that have different widths and heights, like so:
width: 50%; /* this is variable*/
height: 160px; /* this is also variable*/
padding: 10px;
box-sizing: border-box;
display: inline-block;
vertical-align: top;
现在这已经可以了,但是:您看到框4
和5
上方的空白了吗?我可以编写一个纯CSS布局,使这些框填满1
下面的空间吗?我看到了一些伸缩框解决方案,但它们似乎可以使用固定的一组列,理想情况下,我只想在布局中传递1-6号框,并且它们可以正确调整.现代CSS有可能吗?我没有浏览器限制,可以使用任何现代功能!
Now this already works quite okish, but: You see the gap above boxes 4
and 5
? Can I write a pure CSS layout that makes these boxes fill up the space directly below 1
? I saw some flex-box solutions but they seemed to work with a fixed set of columns, ideally I just want to pass boxes 1-6 in the layout and they adjust properly. Is that possible with modern CSS? I have no browser restrictions and can work with any modern feature!
推荐答案
@staypuftman在评论中指出可以使用CSS网格,因此我完成了我想做的事情.这是我的代码:
@staypuftman pointed out in a comment to use CSS grids and I accomplished what I wanted to do. This is my code:
在容器上:
display: grid;
grid-template-columns: repeat(8, 1fr);
grid-template-rows: repeat(12, 1fr);
grid-gap: 15px;
height: 100vh;
我要做的是使用网格布局,通过在grid-template-columns
中写入1fr 8次和在grid-template-rows
属性中使用12个fr
写入12行来创建8列.另外,我将每个项目之间的间距设置为grid-gap
,并将高度设置为100vh,以使网格覆盖整个可见空间.
what I do is I use the grid layout, I create 8 columns by writing 1fr 8 times in grid-template-columns
and 12 rows with the 12 fr
s in the grid-template-rows
property. Also I set a grid-gap
for spacing between each item and a height of 100vh to make my grid span over the whole visible space.
现在在我的物品中,我这样做:
Now within my items I do this:
grid-column-end: span 2;
grid-row-end: span 2;
grid-column-end: span X
告诉浏览器将该项目扩展到我的2列(我创建了8列)中,并且对于具有grid-row-end
的行也是如此.
Where grid-column-end: span X
tells the browser to span the item over 2 of my columns (of which I created 8) and the same in regards to rows with grid-row-end
.
这是结果:
这篇关于没有定义列的纯CSS砌体布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!