csscss-grid

CSS Grid auto fit with max-content


I have 4 columns. The actual content for columns 1 and 4 is 150px, column 2 is 250px and column 3 is 370px. I want to wrap the columns when the browser width changes. When I decrease the width of the browser, I want each column to shrink down to their lowest width before wrapping. So I imagine the 4th column would fall to the next row with a 100% width after it fell below 150px width.

Here's what I thought should've done the trick:

repeat(auto-fit, minmax(max-content, 1fr))

Is there a way to achieve this without passing a fixed width where 'max-content' is?

Here's my solution using media queries and hard widths

https://jsfiddle.net/9hjb5qv8/

Here's the html/css I used in the fiddle above:

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(370px, 1fr));
  grid-gap: 8px;
}

@media (max-width: 799px) {
  .container {
      grid-template-columns: minmax(max-content, 1fr);
  }
}

@media (min-width: 800px) {
  .container .p2,
  .container .p3 {
    grid-column: auto / span 2;
  }
}

.container > div {
  background-color: gray;
  text-align: center;
}
<div class="container">
  <div class="p1">
    <img src="https://via.placeholder.com/150x150">
  </div>
  <div class="p2">
    <img src="https://via.placeholder.com/250x150">
  </div>
  <div class="p3">
    <img src="https://via.placeholder.com/370x150">
  </div>
  <div class="p4">
    <img src="https://via.placeholder.com/150x150">
  </div>
</div>


Solution

  • I had a similar question when playing around with grid:

    grid-template-columns: repeat(auto-fit, minmax(max-content, 1fr))

    If we take a look at the documentation we can see that minmax command is valid: https://developer.mozilla.org/en-US/docs/Web/CSS/minmax

    But in a repeat documentation on csswg, it states one simple rule that disallows all of this from happening; https://drafts.csswg.org/css-grid/#funcdef-repeat

    The generic form of the repeat() syntax is, approximately,

    repeat( [ <positive-integer> | auto-fill | auto-fit ] , <track-list> )

    The first argument specifies the number of repetitions. The second argument is a track list, which is repeated that number of times.

    However, there are some restrictions:

    • The repeat() notation can’t be nested.

    • Automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes.

    Whats an intrinsic or flexible sizes ?

    • An intrinsic sizing function (min-content, max-content, auto, fit-content()).

    So the command wont work in grid because each column/row will be different sizes and wrapping cannot take place. See bellow picture as example.

    minmax max-content auto-fit

    This behavior should be executed using flex-box instead.