css 如何动态重复格网模板区域

zy1mlcev  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(101)

我有一个网站上的WordPress和一个部分,用户添加任何数量的照片。该部分是用网格。现在的问题是,默认情况下有10张照片在该部分。但当用户添加更多,网格打破。我如何使网格重复?

.grid {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 30px;
  grid-template-areas: "one two three four five" "six six seven seven eight" "nine ten seven seven eight";
}

.grid .grid-item:nth-child(1) {
  grid-area: one;
}

.grid .grid-item:nth-child(2) {
  grid-area: two;
}

.grid .grid-item:nth-child(3) {
  grid-area: three;
}

.grid .grid-item:nth-child(4) {
  grid-area: four;
}

.grid .grid-item:nth-child(5) {
  grid-area: five;
}

.grid .grid-item:nth-child(6) {
  grid-area: six;
}

.grid .grid-item:nth-child(7) {
  grid-area: seven;
}

.grid .grid-item:nth-child(8) {
  grid-area: eight;
}

.grid .grid-item:nth-child(9) {
  grid-area: nine;
}

.grid .grid-item:nth-child(10) {
  grid-area: ten;
}
<div class="grid">
  <div class="grid-item">GridItem1</div>
  <div class="grid-item">GridItem2</div>
  <div class="grid-item">GridItem3</div>
  <div class="grid-item">GridItem4</div>
  <div class="grid-item">GridItem5</div>
  <div class="grid-item">GridItem6</div>
  <div class="grid-item">GridItem7</div>
  <div class="grid-item">GridItem8</div>
  <div class="grid-item">GridItem9</div>
  <div class="grid-item">GridItem10</div>
</div>

xqnpmsa8

xqnpmsa81#

如果你想有一个重复的行为,不要使用网格区域。简单地定义列数或行数。我写了一篇关于这种技术的详细文章:https://css-tricks.com/exploring-css-grids-implicit-grid-and-auto-placement-powers/

.grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 30px;
}
.grid > * {
  border: 1px solid red;
}
.grid .grid-item:nth-child(10n + 6) {
  grid-column: 1/span 2;
}
.grid .grid-item:nth-child(10n + 7) {
  grid-column: 3/span 2;
}
.grid .grid-item:nth-child(10n + 7),
.grid .grid-item:nth-child(10n + 8) {
  grid-row: span 2;
}
<div class="grid">
  <div class="grid-item">GridItem 1</div>
  <div class="grid-item">GridItem 2</div>
  <div class="grid-item">GridItem 3</div>
  <div class="grid-item">GridItem 4</div>
  <div class="grid-item">GridItem 5</div>
  <div class="grid-item">GridItem 6</div>
  <div class="grid-item">GridItem 7</div>
  <div class="grid-item">GridItem 8</div>
  <div class="grid-item">GridItem 9</div>
  <div class="grid-item">GridItem 10</div>
  <div class="grid-item">GridItem 11</div>
  <div class="grid-item">GridItem 12</div>
  <div class="grid-item">GridItem 13</div>
  <div class="grid-item">GridItem 14</div>
  <div class="grid-item">GridItem 15</div>
  <div class="grid-item">GridItem 16</div>
  <div class="grid-item">GridItem 17</div>
  <div class="grid-item">GridItem 18</div>
  <div class="grid-item">GridItem 19</div>
  <div class="grid-item">GridItem 20</div>
</div>

相关问题