2

I'm trying to create a row of a non-fixed number of cells that presents the following properties:

  • The cells should only be the size of their content, not more, not less;
  • The row should only be the size of its cells (+ gap), not stretch or shrink under any circumstance);
  • The row should break lines only when forced by the surrounding layout to prevent an overflow, much like flex-wrap: row wrap;
  • The row should "force" its size on the surrounding layout as long as nothing overflows (so if the row is brother to a flex-grow: 1 div, the row shouldn't break its line);
  • If possible, all this without setting any style to the cells, and without media queries;

I can do that with flex and row wrap but I'm wondering if it's possible with display: grid.

Here is what I tried :

.grid {
  display: grid;
  gap: 18px 18px;
  grid-template-columns: repeat(auto-fit, minmax(0, auto));
  border: 1px solid red;
}

.grid > * {
  border: 1px solid blue;
}
<div class='grid'>
  <div>aaa</div>
  <div>aaaaa</div>
  <div>aa</div>
  <div>aaaa</div>
</div>

That's taking up too much space. Using auto-fill makes it shrink too much. How could I do that?

Adriano
  • 3,788
  • 5
  • 32
  • 53
ostrebler
  • 940
  • 9
  • 32
  • You can't AFAIK. `autofit` requires at least one "hard" minmax number (0 doesn't count). Frankly, `display:inline-block` would seem to suit your requirements rather than css-grid. – Paulie_D Apr 26 '19 at 06:52
  • https://gridbyexample.com/examples/example37/ – Paulie_D Apr 26 '19 at 06:53
  • @Paulie_D Yes I played a bit around with `auto-fit` vs `auto-fill`, none really seemed to do the trick. So basically there would be `flex` or `inline-block`. I'll stick with `flex` I guess. – ostrebler Apr 26 '19 at 06:58
  • 1
    this may probably help you understand the limitation of CSS grid: https://stackoverflow.com/q/55064488/8620333 – Temani Afif Apr 26 '19 at 09:21
  • This is not an answer but may help understand auto-fit and auto-fill. https://stackoverflow.com/questions/43129360/css-grid-wrapping. – Simon_Weaver Jul 19 '20 at 19:19

0 Answers0