Why are my template areas not stacking as I expect?

…衆ロ難τιáo~ 提交于 2019-12-11 12:25:30

问题


Using the following 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>

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>

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?


回答1:


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>


来源:https://stackoverflow.com/questions/55325139/why-are-my-template-areas-not-stacking-as-i-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!