我不明白为什么这些方块的高度会一个接一个地移动。我该如何解决这个问题?
我想确保方块不会一个接一个地移动。
.container-grid {
display: grid;
grid-template-columns: 300px 1fr;
grid-template-rows: auto auto;
grid-template-areas:
"one two"
"one two";
grid-gap: 30px;
}
.aa {
background-color: pink;
grid-area: one;
}
.bb {
background-color: red;
grid-area: two;
}
<div class="container-grid">
<div class="aa">It's empty. Why is it moving behind the second block?</div>
<div class="bb">
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
</div>
</div>
在 CSS 代码中,您已将 grid-template-rows 属性定义为“auto auto”。这意味着网格中的行将根据单元格的内容自动调整其高度。
在 HTML 代码中,第二个块(带有“bb”类的 div)包含更多内容,因此需要更多高度。结果,第一个块(类为“aa”的 div)被下推以适应第二个块的高度。
如果您想防止块垂直移动并保持两个块的高度一致,您可以为网格中的行设置固定高度。这是一个例子:
.container-grid {
display: grid;
grid-template-columns: 300px 1fr;
grid-template-rows: 200px 200px; /* Set a fixed height for the rows */
grid-template-areas:
"one two"
"one two";
grid-gap: 30px;
}
在此示例中,网格中的两行的固定高度均为 200 像素。这可确保两个块保持相同的高度并且不会垂直移动。
可根据您的要求随意调整高度值。
或者,如果您希望行根据内容动态调整其高度,您可以删除固定高度并接受网格的自然行为,其中行将根据单元格的内容调整大小。