如何工作的css网格-自动排版?

2022-04-02 00:00:00 css css-grid

我面对的问题是,我不了解隐式网格是如何工作的。我阅读了文档、MDN和其他一些资源。但还有一个问题尚未解决。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
.grid {
  display: grid;
  grid-template: repeat(2, 100px) / repeat(6, 1fr);
  grid-gap: 1rem;
  font-size: 2rem;
}

.grid__item {
  background-color: #BDBDBD;
}

.grid__item--1 {
  grid-row: 1 / -1;
}

.grid__item--5 {
  grid-row: 1 / -1;
}
<div class="grid">
  <div class="grid__item grid__item--1">1</div>
  <div class="grid__item grid__item--2">2</div>
  <div class="grid__item grid__item--3">3</div>
  <div class="grid__item grid__item--4">4</div>
  <div class="grid__item grid__item--5">5</div>
  <div class="grid__item grid__item--6">6</div>
</div>

结果如下:

为什么第五个块在第二个块之前?

编码:https://jsfiddle.net/serhioses/51do02xa/


解决方案

您需要的内容已定义in this part of the specification我们最初拥有的位置:

  1. 处理锁定到给定行的项目。

对于具有明确行位置的每个网格项目(即,grid-row-startgrid-row-end属性定义明确的网格位置),按修改顺序的文档顺序:

然后

  1. 定位剩余的网格项。

因此,基本上我们将显式放置在行内的项(grid-row-startgrid-row-end都应不同于auto)放置,然后根据上述规范中描述的算法放置另一个项。

即使您修改了订单,也会得到相同的结果:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
.grid {
  display: grid;
  grid-template: repeat(2, 100px) / repeat(6, 1fr);
  grid-gap: 1rem;
  font-size: 2rem;
}

.grid__item {
  background-color: #BDBDBD;
}

.grid__item--1 {
  grid-row: 1 / -1;
}

.grid__item--5 {
  grid-row: 1 / -1;
  order:100;
}
<div class="grid">
  <div class="grid__item grid__item--1">1</div>
  <div class="grid__item grid__item--2">2</div>
  <div class="grid__item grid__item--3">3</div>
  <div class="grid__item grid__item--4">4</div>
  <div class="grid__item grid__item--5">5</div>
  <div class="grid__item grid__item--6">6</div>
</div>

相关文章