What I wanna do is to make a CSS grid with a dynamic number of cells. For the sake of simplicity, let\'s assume there will always be four cells per row. Can I specify a grid
Okay, after reading the MDN reference, I found the answer! The key to dynamic rows (or columns) is the repeat property.
const COLORS = [
'#FE9',
'#9AF',
'#F9A',
"#AFA",
"#FA7"
];
function addItem(container, template) {
let color = COLORS[_.random(COLORS.length - 1)];
let num = _.random(10000);
container.append(Mustache.render(template, { color, num }));
}
$(() => {
const tmpl = $('#item_template').html()
const container = $('#app');
for(let i=0; i<5; i++) { addItem(container, tmpl); }
$('#add_el').click(() => {
addItem(container, tmpl);
})
container.on('click', '.del_el', (e) => {
$(e.target).closest('.item').remove();
});
});
.container {
width: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(auto-fill, 120px);
grid-row-gap: .5em;
grid-column-gap: 1em;
}
.container .item {
}
{{ num }}
P.S. Or you can use grid-auto-rows in my particular example.