向内拉动网格项 - "grid squeeze"



我的网格布局有2列。它包含全宽项目的混合物,这些项目占据了网格的全宽;以及各占一行宽度的一半的半宽度项目。半宽的东西总是成对的。最左边的项目应该向右拉,最右边的项目应该向左拉,实际上是挤在一起的。

我准备了一个使用Tailwind样式CSS的例子,展示了我想要的东西:

.m-2 { margin: 0.5rem; }
.p-2 { padding: 0.5rem; }
.bg-blue { background-color: rgba(0, 0, 255, 0.5); }
.bg-red { background-color: rgba(255, 0, 0, 0.5); }
.grid { display: grid; }
.grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.col-span-2 { grid-column: span 2 / span 2; }
.justify-self-start { justify-self: start; }
.justify-self-end { justify-self: end; }
<div class="grid grid-cols-2">
<div class="col-span-2 m-2 p-2 bg-blue">
<p>Full width item</p>
</div>
<div class="justify-self-end m-2 p-2 bg-red">
<p>Half width item</p>
</div>
<div class="justify-self-start m-2 p-2 bg-red">
<p>Half width item</p>
</div>
<div class="col-span-2 m-2 p-2 bg-blue">
<p>Full width item</p>
</div>
</div>

然而,在我的场景中,任何单个网格项都只知道它是全宽还是半宽。如果它是全宽的,它可以将自己设置为跨越2列。如果它是半宽的,它可以将自己设置为跨1列,但它不知道是向左还是向右拉。

当一个单独的项目不知道它是半宽行中的第一个还是第二个项目时,我如何告诉它向左或向右拉?


连续处理3个项目的解决方案的加分,中间一个项目位于中心。

对于使用grid-auto-flow将不连续出现在HTML中的半角元素相邻放置的解决方案,可以获得额外的积分。

我唯一能想到的只使用CSS解决问题的方法是为布局设置不同的元素,然后使用第n个类型:

.container {
display: grid;
grid-template-columns: 200px 200px;
grid-auto-flow: row dense;
grid-gap: 4px;
}
span {
grid-column: span 2;
background-color: lightblue;

}
p {
width: 70px;
background-color: lightgreen;
}
p:nth-of-type(odd) {
justify-self: end;
}
<div class="container">
<span>full</span>
<span>full</span>
<p>half</p>
<span>full</span>
<p>half</p>
<p>half</p>
<span>full</span>
<p>half</p>
<p>half</p>
<p>half</p>
</div>

最新更新