如何防止项目高度扩展从扩展其他项目在同一行- CSS网格/flex?



我正在尝试制作一个3x3的网格,其中包含可以扩展和折叠的项目。当用户单击一个项目时,该项目将展开,并将其下方的项目推到同一列,但同一行中的其他项目将保持其默认高度。

应用程序是一个VueJS应用程序。我已经尝试使用display: griddisplay: flex,但这两种解决方案将改变整个行的高度,以匹配扩展项的新高度。


// flex solution
.container {
display: flex;
justify-content: space-evenly;
flex-flow: row wrap;
}
//...
.item {
min-width: 33.33%;
height: auto;
}
// grid solution
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(150px, auto)
}

如何防止其他项目受到扩展项目的新高度的影响?

所以经过更多的搜索,我发现我需要的实际布局风格与砌体/马赛克模式一致。既然我现在知道了这个名字,我可以做更具体的谷歌搜索,并找到Tobias Ahlin写的一篇博客文章,其中有一个解决方案。

https://tobiasahlin.com/blog/masonry-with-css/

要点是,你需要有流动方向是列,而被包装,然后使用:nth-child对元素排序。


/* Render items as columns */
.container {
display: flex;
flex-flow: column wrap;
}

/* Re-order items into rows */
.item:nth-child(3n+1) { order: 1; }
.item:nth-child(3n+2) { order: 2; }
.item:nth-child(3n)   { order: 3; }

/* Force new columns */
.container::before,
.container::after {
content: "";
flex-basis: 100%;
width: 0;
order: 2;
}

如果我是诚实的,我真的不知道为什么这工作。它还会根据容器和项目的高度意外地表现。

希望这能帮助到那些对这个看似简单的设计布局有问题的人!

最新更新