我有一个CSS 网格布局,如下所示:

这对我来说非常有效,但是当我降低屏幕分辨率时,网格的响应能力使网格看起来像这样:

相反,我希望包装项目能够对齐左右空白,它们应该如下所示:

我怎样才能实现上述目标?这些项目在数量上是动态的。可以有偶数个项目,这将使它看起来更好,因为左右空白将等距。但是,如果项目的数量是奇数,则空格仍应均匀分布。我尝试使用grid-auto-flowand align-items,但它们似乎没有帮助。
.accordioninnergrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
.innerbox {
display: flex;
border: 1px solid black;
flex-direction: column;
align-items: center;
word-wrap: break-word;
width: auto;
}
.innerbox>p,
img {
margin: 1%;
}Run Code Online (Sandbox Code Playgroud)
<div class="accordioninnergrid">
<div class="innerbox">
<img src="some-image" width="50%" height="50%" />
<p>
This is the text
</p>
<p>
Small Tagline
</p>
</div>
<div class="innerbox">
<img src="some-image" width="50%" height="50%" />
<p>
This is the text
</p>
<p>
Small Tagline
</p>
</div>
<div class="innerbox">
<img src="some-image" width="50%" height="50%" />
<p>
This is the text
</p>
<p>
Small Tagline
</p>
</div>
<div class="innerbox">
<img src="some-image" width="50%" height="50%" />
<p>
This is the text
</p>
<p>
Small Tagline
</p>
</div>
<div class="innerbox">
<img src="some-image" width="50%" height="50%" />
<p>
This is the text
</p>
<p>
Small Tagline
</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
这是 Grid 或 Flex 的一个有问题的布局。两者都没有简单的解决方案。
使用 Grid,无法自动将项目放置在中间列中。网格如何知道它需要将网格项放置在第 3、4 和 5 列中,以便它们看起来居中?
更糟糕的是,如果只有四列和一项居中怎么办?该项目必须跨越第 2 列和第 3 列。
没有网格函数可以自动执行此操作。它必须是作者定义的。
有了 Flex,上述问题就不存在了。但需要权衡。Flex 有一个 Grid 没有的问题。
它源于这一段代码:
.accordioninnergrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
Run Code Online (Sandbox Code Playgroud)
该grid-template-columns规则规定每列的最小宽度可以为 240px,最大宽度为1fr(即所有可用空间)。
在 flex 中,用来代替fr函数的属性是flex-grow。
但是,由于在弹性容器中不存在阻碍跨线移动的列轨道,flex-grow因此可以自由地在整条线上扩展项目。
简而言之,flex-grow和居中不能共存。
如果flex-grow被删除,那么你用 flex 居中就没有问题了。但是,当然,还会有另一个权衡:您将失去可用空间功能的消耗:
.accordioninnergrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
Run Code Online (Sandbox Code Playgroud)
.accordioninnergrid {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.innerbox {
flex: 1 0 140px; /* fg, fs, fb -- try fg: 0 */
display: flex;
border: 1px solid black;
flex-direction: column;
align-items: center;
word-wrap: break-word;
}
.innerbox > p,
img {
margin: 1%;
}Run Code Online (Sandbox Code Playgroud)
更多详细信息请参见此处:
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |