我在做一个关于 CSS grid 的在线测验,我被其中一个问题弄糊涂了。
问题来了:
假设我们有一个具有以下 CSS 属性的网格,其中有 4 个框。如果我们在 HTML 中添加第五个框,它的宽度是多少?
这是代码:
.grid {
grid-template-rows: repeat(2, 50px);
grid-template-columns: repeat(2, 100px);
grid-auto-rows: 60px;
grid-auto-columns: 70px;
}
我的想法是:所以已经有四个盒子了,如果我们要添加一个新盒子,它会触发'grid-auto-rows'和'grid-auto-columns'。所以它的宽度是 70 像素。
但答案是:
新框仍将位于明确定义的列之一中,每列 100 像素。
为什么新框会出现在明确定义的列之一中?里面不是已经有四个人了么?
第五项的宽度确实是 100px,如
grid-template-columns
所定义。
这就是为什么:
最初的四个框创建一个 2x2 网格,正如您在网格容器中定义的那样:
article {
display: grid;
grid-template-rows: repeat(2, 50px);
grid-template-columns: repeat(2, 100px);
grid-auto-rows: 60px;
grid-auto-columns: 70px;
}
section {
background-color: lightgreen;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
font-size: .9em;
}
<article>
<section>100 x 50</section>
<section>100 x 50</section>
<section>100 x 50</section>
<section>100 x 50</section>
</article>
然后你添加第五个项目。该项目不在明确的网格区域。
grid-auto-flow
属性。
此属性控制未明确放置的网格项(又名“自动放置项”)的放置。
它的默认值是
row
,这意味着自动放置的项目逐行排列,填充每一行,并根据需要添加新行。
因为您的网格容器默认为
grid-auto-flow: row
,并且所有显式行都已填充,在隐式网格中创建一个新行以容纳第五项.
第五项在第 1 列第 3 行结束。
第 1 列已经存在。它由
grid-template-columns
创建,宽度为100px。
第 3 行是新的和隐含的。它的高度是 60px,定义在
grid-auto-rows
.
article {
display: grid;
grid-template-rows: repeat(2, 50px);
grid-template-columns: repeat(2, 100px);
grid-auto-rows: 60px;
grid-auto-columns: 70px;
}
/* non-essential demo styles */
section {
background-color: lightgreen;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
font-size: .9em;
}
<article>
<section>100 x 50</section>
<section>100 x 50</section>
<section>100 x 50</section>
<section>100 x 50</section>
<section>100 x <b>60</b></section>
</article>
如果您改为使用
grid-auto-flow: column
,那么自动放置的项目将垂直流动,填充列并根据需要创建新的列。那么你的第五个项目将是 70px 宽。
article {
display: grid;
grid-template-rows: repeat(2, 50px);
grid-template-columns: repeat(2, 100px);
grid-auto-rows: 60px;
grid-auto-columns: 70px;
grid-auto-flow: column; /* new */
}
/* non-essential demo styles */
section {
background-color: lightgreen;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
font-size: .9em;
}
<article>
<section>100 x 50</section>
<section>100 x 50</section>
<section>100 x 50</section>
<section>100 x 50</section>
<section><b>70</b> x 50</section>
</article>