I have a project where I want to use a grid. I have found a very easy way in order to display a random set of child elements inside a div. I use auto-fit together with minmax in order to automatically give the elements the same width and when they exceed certain thresholds they go to the next row.
The problem is that it works fine when I use a max of 1fr. The items scale and take up the maximum amount of width. But the problem is that when I have a small amount of items (1 or 2). Then the children get way to large in width.
So in order to combat this I have set the max to a set amount. But now they don't scale anymore and instantly jump to the next line.
.working{
width: 100%;
height: 5rem;
margin-bottom: 3rem;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(5rem, 1fr));
gap: 1rem;
}
.not-working{
width: 100%;
height: 5rem;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(5rem, 8rem));
gap: 1rem;
}
.item{
background-color: red;
}
<div class='working'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
<div class='not-working'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
Is auto-fill
or just auto
be what you would expect ?
.working {
width: 100%;
height: 5rem;
margin-bottom: 3rem;
justify-content: start;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(5rem, auto));
gap: 1rem;
}
.item {
background-color: red;
min-width:min-content;
}
.not.working {
grid-template-columns: repeat(auto-fit, minmax(5rem, auto));
}
<div class='working'>
<div class='item'>plap plap plap plap</div>
<div class='item'>plip plip</div>
<div class='item'>plop plop plop plop plop plop plop plop plop plop</div>
<div class='item'>.</div>
</div>
<div class='not working'>
<div class='item'>plap plap plap plap</div>
<div class='item'>plip plip</div>
<div class='item'>plop plop plop plop plop plop plop plop plop plop</div>
<div class='item'>.</div>
</div>