CSS Grid auto fit with max-content

Hectooorr picture Hectooorr · Oct 11, 2018 · Viewed 10.6k times · Source

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:

Answer

Kivylius picture Kivylius · Dec 11, 2018

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.