使网格项目占用剩余空间

时间:2018-11-10 00:26:41

标签: html css css3 grid css-grid

thumbnail x 4,一列可以填充3个缩略图,第4列位于下方,并填充其余空间(不添加新类)。

.tile {
  max-width: 350px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.thumbnail {
  padding: 20px;
  height: auto;
  background-color: #ff0099;
  color: #fff;
}
<div class="item tile">
  <div class="thumbnail">Grid - Thumbnail #1</div>
  <div class="thumbnail">Grid - Thumbnail #2</div>
  <div class="thumbnail">Grid - Thumbnail #3</div>
  <div class="thumbnail">Grid - Thumbnail #4</div>
</div>

1 个答案:

答案 0 :(得分:2)

  

(不添加新类)

嗯,这几乎排除了CSS Grid。您需要一条新规则来告诉最后一项展开:

.tile {
  max-width: 350px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.thumbnail {
  padding: 20px;
  background-color: #ff0099;
  color: #fff;
}

 /* new */
.thumbnail:last-child {
  grid-column: 1 / -1;
}
<div class="item tile">
  <div class="thumbnail">Grid - Thumbnail #1</div>
  <div class="thumbnail">Grid - Thumbnail #2</div>
  <div class="thumbnail">Grid - Thumbnail #3</div>
  <div class="thumbnail">Grid - Thumbnail #4</div>
</div>

Flexbox无需添加新类即可工作:

.tile {
  max-width: 350px;
  display: flex;
  flex-wrap: wrap;
}

.thumbnail {
  flex: 1 0 95px;  /* flex-grow, flex-shrink, flex-basis */
  margin: 5px;
  padding: 10px;
  background-color: #ff0099;
  color: #fff;
  box-sizing: border-box;
}
<div class="item tile">
  <div class="thumbnail">Grid - Thumbnail #1</div>
  <div class="thumbnail">Grid - Thumbnail #2</div>
  <div class="thumbnail">Grid - Thumbnail #3</div>
  <div class="thumbnail">Grid - Thumbnail #4</div>
</div>