我正在尝试制作一个 2 列和 4 行的网格,我希望以这种方式填充单元格:
'image empty-cell'
'image text'
'image text'
'image empty-cell'
我已经尝试过以这种方式执行此操作但它不起作用,因为第二列的第一行和最后一行单元格不为空:
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr 1fr;
grid-template-areas:
"image ."
"image header"
"image paragraph"
"image .";
}
.img {
grid-area: image;
}
<div class="container">
<img class="img" src="https://josepicado.com/portfolio/stackoverflow/img.png">
<h1>Stack overflow logo on the left</h1>
<p>Stack overflow logo on the left</p>
</div>
但是如果我将 grid-area 属性也分配给 h1 和 p 元素(下面的代码),它会起作用,为什么?
h1 {
grid-area: header;
}
p {
grid-area: paragraph;
}
我认为 CSS 在任何情况下都会将单元格留空,不仅是在所有元素都分配了 grid-area 属性的情况下。
最佳答案
来自 the specification :
This property specifies named grid areas, which are not associated with any particular grid item, but can be referenced from the grid-placement properties. ref
然后
A sequence of one or more "." (U+002E FULL STOP), representing a null cell token.
A null cell token represents an unnamed area in the grid container.
基本上,使用 grid-template-area
可以定义命名和未命名区域,这些区域不与任何元素关联并且是空的。您可以明确引用一个区域来放置元素,或者该区域可用于自动放置元素
An item can be placed into a named grid area (such as those produced by the template in grid-template-areas) by specifying the area’s name in grid-area
和
A grid item can be automatically placed into the next available empty grid cell, growing the grid if there’s no space left.
在您的示例中,如果您未定义任何内容,您将拥有:
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr 1fr;
grid-template-areas:
"image ."
"image header"
"image paragraph"
"image .";
border:1px solid;
height:300px;
}
<div class="container">
<img class="img" src="https://josepicado.com/portfolio/stackoverflow/img.png">
<h1>Stack overflow logo on the left</h1>
<p>Stack overflow logo on the left</p>
</div>
图像将放置在第一个空单元格(第一个 image
区域)。标题在下一个(第一个 .
区域)。下一个p
(第二个image
区域)
通过明确指定图像的位置,另一个将自动放置在第一个.
区域和header
一个
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr 1fr;
grid-template-areas:
"image ."
"image header"
"image paragraph"
"image .";
border:1px solid;
height:300px;
}
img {
grid-area:image;
}
<div class="container">
<img class="img" src="https://josepicado.com/portfolio/stackoverflow/img.png">
<h1>Stack overflow logo on the left</h1>
<p>Stack overflow logo on the left</p>
</div>
换句话说,命名和未命名区域是完全一样的。唯一的区别是你可以用它的名字引用第一个,而不能用第二个。未命名区域可以通过其索引进行引用。
关于css - 为什么必须将 grid-area 属性设置为所有 html 元素以留下空单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57884928/