如何为未使用的最少空间指定CSS网格列

时间:2018-07-20 17:08:51

标签: css css3 css-grid

假设我有许多项目布置在等宽的网格单元中,如何指定列,以免它们留下多余的未使用空间?

原始网格(右侧有空间浪费)示例:

const COLOURS = [
  'navy',
  'green',
  'maroon',
  '#80B0BF',
  '#006241',
  '#573862'
]

window.addEventListener('load', () => {
  const grid = document.getElementById('grid')
  
  for (let i = 0; i < 20; i++) {
    let el = document.createElement('div')
    el.classList.add('element')
    el.style.backgroundColor = _.sample(COLOURS)
    grid.appendChild(el)
  }
})
.grid {
  display: grid;
  width: 400px;
  border: 3px solid black;
  grid-template-columns: repeat(auto-fit, 100px);
  grid-gap: 10px;
}

.element {
  padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

<div class="grid" id="grid">
</div>

1 个答案:

答案 0 :(得分:2)

使用minmax(<constant value>, 1fr)自动扩展行。

const COLOURS = [
  'navy',
  'green',
  'maroon',
  '#80B0BF',
  '#006241',
  '#573862'
]

window.addEventListener('load', () => {
  const grid = document.getElementById('grid')
  
  for (let i = 0; i < 20; i++) {
    let el = document.createElement('div')
    el.classList.add('element')
    el.style.backgroundColor = _.sample(COLOURS)
    grid.appendChild(el)
  }
})
.grid {
  display: grid;
  width: 400px;
  border: 3px solid black;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-gap: 10px;
}

.element {
  padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
<div class="grid" id="grid">
</div>