为什么我的模板区域没有按预期堆叠? [英] Why are my template areas not stacking as I expect?

查看:56
本文介绍了为什么我的模板区域没有按预期堆叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下CSS:

.container {
  display : grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-template-areas:
    'first second'
    'first second'
;
}

.first {
  grid-area: first;
  width: 200px;
  height: 200px;
  background-color: red;
}

.second {
  grid-area: second;
  width: 200px;
  height: 200px;
  background-color: #0eb5d6;

这些盒子将堆叠(显示为一个红色,一个蓝色):

These boxes will stack (appearing as one red, 1 blue):

  <div class="container">
    <div class="first"></div>
    <div class="second"></div>
    <div class="first"></div>
    <div class="second"></div>
  </div>

但是,这些不会堆叠,并正确显示为具有相同CSS的2行:

However, these will not stack, and correctly appear as 2 rows with the same css:

  <div class="container">
    <div class="first"></div>
    <div class="second"></div>
  </div>

  <div class='container'>
    <div class="first"></div>
    <div class="second"></div>
  </div>

在我的实际用例中,我尝试使用CSS网格对齐表单。如果可能,我不想在行中使用div。还是这是避免将元素堆叠成一行的唯一方法?

In my actual use case I'm trying to align a form using css grid. I would like to not need divs for rows if possible. Or is this the only way to avoid stacking of elements into one row?

推荐答案

请注意,这里的 grid -template-areas 形成一个矩形,因此第一第二 spans 他们的列。并且多个声明只会重叠:

Note that here grid-template-areas form a rectangle and so first and second spans their columns. And multiple declaration will only overlap:


为列出的每个单独的字符串创建一行,为每个字符串创建一个列
字符串中的单元格。
中以及行之间的多个命名单元标记创建了一个跨
对应网格单元的单个命名网格区域。除非这些单元格形成矩形,否则
声明无效。

A row is created for every separate string listed, and a column is created for each cell in the string. Multiple named cell tokens within and between rows create a single named grid area that spans the corresponding grid cells. Unless those cells form a rectangle, the declaration is invalid.

MDN

您可以删除 网格模板区域-如果没有它,效果很好。参见下面的演示:

You can remove grid-template-areas here - it works fine without it. See demo below:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.first {
  width: 200px;
  height: 200px;
  background-color: red;
}

.second {
  width: 200px;
  height: 200px;
  background-color: #0eb5d6;
}

<div class="container">
  <div class="first"></div>
  <div class="second"></div>
  <div class="first"></div>
  <div class="second"></div>
</div>

这篇关于为什么我的模板区域没有按预期堆叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆