gpt4 book ai didi

css - 网格模板区域和网格模板列之间的关系

转载 作者:行者123 更新时间:2023-11-28 10:59:09 25 4
gpt4 key购买 nike

我是编码新手,似乎没有正确理解 CSS 网格模型。在下面的代码中,网格被分成 3 个网格模板列(每列 300px),但是网格模板区域中每行有 8 个单元(例如:hd hd hd hd hd hd hd hd)而不是 3这对我来说没有意义。有人可以帮我理解为什么网格模板区域中的单位数与列数不同吗? (所以如果有 3 列,它将是“hd hd hd”)。他们是什么关系?

.container {
display:grid;
grid-template-columns: 300px 300px 300px;
grid-template-rows: 250px 600px;
grid-template-areas:
"hd hd hd hd hd hd hd hd"
"sd sd sd main main main main main"
"ft ft ft ft ft ft ft ft";
}

最佳答案

通过定义模板区域,您定义了一个包含 8x3 项的网格。默认情况下,这些元素将具有自动宽度和自动高度,如下所示:

.container {
display:grid;
grid-template-areas:
"hd hd hd hd hd hd hd hd"
"sd sd sd main main main main main"
"ft ft ft ft ft ft ft ft";
border:1px solid;
}
<div class="container">

</div>

高度将为 0,因为没有内容,容器的宽度将平均分配到 8 列。

如果您添加模板列/行,您将明确定义网格轨道的宽度/高度。通过在 grid-template-columns 中只定义 3 个数字,您将只为前 3 列定义宽度,而其他列将保持 auto。与 grid-template-rows

相同的逻辑

.container {
display:grid;
grid-template-columns: 50px 50px 50px;
grid-template-rows: 50px 60px;
grid-template-areas:
"hd hd hd hd hd hd hd hd"
"sd sd sd main main main main main"
"ft ft ft ft ft ft ft ft";
border:1px solid;
}
<div class="container">

</div>

如果我考虑上面的代码,您将对列使用 50px 50px 50px auto auto auto auto auto,对行使用 50px 60px auto


为了更准确,这里是sepcification的描述:

The size of the explicit grid is determined by the larger of the number of rows/columns defined by grid-template-areas and the number of rows/columns sized by grid-template-rows/grid-template-columns. Any rows/columns defined by grid-template-areas but not sized by grid-template-rows/grid-template-columns take their size from the grid-auto-rows/grid-auto-columns properties. ref

如您所见,我们陷入了行/列未按 grid-template-rows/grid-template-columns 调整大小的情况,因此它们的大小将由 grid-auto-rows/grid-auto-columns 定义,其中默认值设置为 auto

您可以调整该值以获得不同的结果:

.container {
display:grid;
grid-template-columns: 50px 50px 50px;
grid-template-rows: 50px 60px;
grid-auto-columns:10px;
grid-auto-rows:20px;
grid-template-areas:
"hd hd hd hd hd hd hd hd"
"sd sd sd main main main main main"
"ft ft ft ft ft ft ft ft";
border:1px solid;
}
<div class="container">

</div>

以上代码将为列使用 50px 50px 50px 10px 10px 10px 10px 10px,为行使用 50px 60px 20px

关于css - 网格模板区域和网格模板列之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58265276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com