在栅格布局内插入全宽块

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

我正在创建Google Images不久前拥有的页面布局。在所选图像下有一个大的带有完整部分的图像网格。我很好奇是否可以使用cssdisaply: grid属性来标记此页面。

一开始我做了一个有三个柱子的容器。一切都很好:

数据-lang="js"数据-隐藏="假"数据-控制台="假"数据-巴贝尔="假">
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}

.item {
  border: 1px solid;
  height: 20px;
}
<div class="container">
  <div class="item"></div>  
  <div class="item"></div>  
  <div class="item"></div>  
  <div class="item"></div>  
</div>

但我不知道如何在此网格中插入描述块。我根本不确定这有没有可能。我将通过display: none | block切换描述。图像和行数未知。

数据-lang="js"数据-隐藏="假"数据-控制台="假"数据-巴贝尔="假">
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
}

.item {
  border: 1px solid;
  height: 20px;
}

.item__description {
  border: 1px solid red;
  height: 10px;
}
<div class="container">
  <div class="item">
    <div class="item__description">Description of the first item</div>
  </div>
  <div class="item"></div>
  <div class="item"></div>  
  <div class="item"></div>
  <div class="item__description">Description of the last item. No matter where to place this description: inside or outside 'item' block</div>
</div>

我们的想法是在没有任何js DOM操作的情况下创建此布局。


解决方案

.container上设置grid-auto-flow: row dense;。将.item__description移出项目,并在其上设置grid-column: 1 / span 3;

数据-lang="js"数据-隐藏="假"数据-控制台="假"数据-巴贝尔="假">
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-flow: row dense;
  grid-gap: 20px;
}

.item {
  border: 1px solid;
  height: 20px;
}

.item__description {
  grid-column: 1 / span 3;
  border: 1px solid red;
  height: 20px;
}
<div class="container">
  <div class="item"></div>
  <div class="item__description">Description of the first item</div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item__description">Description of the last item. No matter where to place this description: inside or outside 'item' block</div>
</div>

这也适用于显示切换(悬停项目):

数据-lang="js"数据-隐藏="真"数据-控制台="假"数据-巴贝尔="假">
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-flow: row dense;
  grid-gap: 20px;
}

.item {
  border: 1px solid;
  height: 20px;
}

.item__description {
  display: none;
  grid-column: 1 / span 3;
  border: 1px solid red;
  height: 20px;
}

.item:hover + .item__description {
  display: block;
}
<div class="container">
  <div class="item">Hover Me 1</div>
  <div class="item__description">Description of the item 1</div>
  <div class="item">Hover Me 2</div>
  <div class="item__description">Description of the item 2</div>
  <div class="item">Hover Me 3</div>
  <div class="item__description">Description of the item 3</div>
  <div class="item">Hover Me 4</div>
  <div class="item__description">Description of the item 4</div>
</div>

相关文章