CSS网格-可重复的模板区域

时间:2019-11-14 12:39:00

标签: css css-grid

我对CSS Grid是否具有创建可重复的grid-template-areas的功能感兴趣?

为解释我创建此示例的功能,

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr) 6rem;
  grid-template-areas:
    '. . . button'
    '. . . button'
    '. . . button'
    '. . . button';
  grid-gap: 1rem;
}
.item {
  background: #add8e6;
  padding: 1rem;
}
.button {
  grid-area: button;
  background: #ffc0cb;
  padding: 1rem;
}
<div class="grid">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="button">Button</div>
</div>

如示例所示,grid-template-areas属性包含多个重复项。 .item元素可能具有无限数,因此,无限grid-template-areas是不可接受的。

我知道这里的解决方案将是.item的嵌套网格,但是我实际上对在单个网格中实现此解决方案感兴趣,例如概念验证。

1 个答案:

答案 0 :(得分:1)

您可以将网格和定位结合在一起,如下所示:

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  padding-right:7rem;
  grid-gap: 1rem;
  position:relative;
}
.item {
  background: #add8e6;
  padding: 1rem;
}
.button {
  position:absolute;
  top:0;
  right:0;
  bottom:0;
  width:6rem;
  background: #ffc0cb;
  padding: 1rem;
  box-sizing:border-box;
}
<div class="grid">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="button">Button</div>
</div>