gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:09:41 25 4
gpt4 key购买 nike

假设我有许多元素,排列在宽度相等的网格单元格中,我该如何指定列,以便它们不会留下额外的未使用空间?

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

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>

最佳答案

使用 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>

关于css - 如何为最少未使用的空间指定 CSS 网格列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51447392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com