I am trying to put some divs in a grid by explicitly assigning rows, columns, and sizes to the elements and allowing CSS grid to do column and row sizing work using the following CSS.
display: grid;
grid-auto-columns: min-content;
The value min-content
is supposed to set columns to be the smallest possible size that fits the content without overflow. However, this is not happening. Even though these elements can all fit in a 350px grid, the third column is too large causing unnecessary whitespace.
Here is an image of what is going on.
And here is the actual code: JSFiddle
function randint(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const children = document.getElementById('parent').children;
const skip = 360 / children.length;
let value = randint(0, 359);
for (let i = 0; i < children.length; i += 1) {
const elm = children[i];
elm.style.backgroundColor = `hsl(${value}, 100%, 85%)`;
value += skip;
elm.id = "w" + (i + 1);
const style = window.getComputedStyle(elm);
elm.innerHTML = `width: ${elm.offsetWidth}px<br \>
col: ${style.getPropertyValue('grid-column')}<br \>
row: ${style.getPropertyValue('grid-row')}`;
}
#parent {
display: grid;
grid-auto-columns: min-content;
border: 1px solid black;
width: 350px;
font-size: 10pt;
}
#parent>div {
display: flex;
justify-content: center;
align-items: center;
height: 75px;
}
#w1 {
width: 200px;
grid-column: 1 / 3;
grid-row: 1 / 2;
}
#w2 {
width: 150px;
grid-column: 3 / 5;
grid-row: 1 / 2;
}
#w3 {
width: 100px;
grid-column: 1 / 2;
grid-row: 2 / 3;
}
#w4 {
width: 150px;
grid-column: 2 / 4;
grid-row: 2 / 3;
}
#w5 {
width: 100px;
grid-column: 4 / 5;
grid-row: 2 / 3;
}
<div id='parent'>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>