让我们来看看你的两个症结所在。
grid-auto-flow: column
is required to make the column wrapping work, but also forces me to add grid-template-rows: repeat(5, 1em)
to specify a row count, which breaks the responsiveness. Is there a way to calculate the row count automatically based on content and column count?
grid-auto-flow: column
does not使列包裹工作。事实上,它的作用恰恰相反。该规则创建新列以容纳其他网格项。
它的工作原理如下(来自规范):
7.7.自动放置:grid-auto-flow财产 https://www.w3.org/TR/css3-grid-layout/#grid-auto-flow-property
未显式放置的网格项会自动放置到
自动放置网格容器中未占用的空间
算法。
grid-auto-flow
控制自动放置算法的工作方式,
准确指定自动放置的项目如何流入网格。
column
自动放置算法通过填充每一列来放置项目
转动,根据需要添加新列。
row
自动放置算法通过依次填充每一行来放置项目,并根据需要添加新行。如果两者都不是row
nor column
提供,row
假设。
关于你的问题:
有没有办法根据内容和列数自动计算行数?
仅凭 CSS Grid,我不这么认为。正如规范中所说,grid-auto-flow
旨在在指定方向添加新轨道(column
/ row
).
如果可以用Grid来完成,那么它就不是全自动的。您至少需要一些定义的位置,我猜还需要媒体查询。
最后,关于列换行,来自auto-fit
or auto-fill
中的值grid-template-columns
and grid-template-rows
特性。
Why are the column widths not evenly distributed and why don't they adapt to the screen size? Isn't this what minmax
is for?
这又回到了上面突出显示的规格部分。
这是您的列大小代码:
grid-template-columns: repeat(auto-fill, minmax(33.333%, 50%));
这翻译为:每个显式列的宽度必须最小为 33.333%,最大为 50%。
问题是第三列不是explicit. It is implicit,因为它是在自动放置算法的指导下添加到网格中的grid-auto-flow: column
。所以本专栏不受grid-template-columns
,它只涉及明确的轨道尺寸 https://www.w3.org/TR/css3-grid-layout/#track-sizing.
的属性为隐式轨道大小调整 https://www.w3.org/TR/css3-grid-layout/#auto-tracks are grid-auto-columns
and grid-auto-rows
。他们的默认值是auto
,这就是您在布局中看到的内容:第三列是其内容的宽度。
ol {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(33.333%, 50%));
grid-auto-flow: column;
grid-template-rows: repeat(5, 1em);
margin: 0;
padding: 0;
list-style: none;
background-color: grey;
}
li {
outline: 1px solid orange;
}
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
<li>Item 12</li>
<li>Item 13</li>
<li>Item 14</li>
<li>Item 15</li>
</ol>
一旦你设置了值grid-auto-columns
,第三列的大小可以适当调整。
ol {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(33.333%, 50%));
grid-auto-flow: column;
grid-template-rows: repeat(5, 1em);
grid-auto-columns: 33.333%; /* NEW */
margin: 0;
padding: 0;
list-style: none;
background-color: grey;
}
li {
outline: 1px solid orange;
}
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
<li>Item 12</li>
<li>Item 13</li>
<li>Item 14</li>
<li>Item 15</li>
</ol>
当然,上面的信息只是为了解释,而不是主要问题的解决方案,因为我不相信 CSS Grid 提供了这样的解决方案。