Search code examples
csscss-grid

CSS fr / fractional units minimum too large


I have a jsfiddle.

What I have: enter image description here

What I want: enter image description here

Problem:

The hopefully relevant section is:

  grid-template-columns: repeat(auto-fit, 1fr);

where both elements in my section have width: max-content;.

This (and the expanded but technically identical form of repeat(auto-fit, minmax(auto, 1fr));) do not do what I expect - it creates picture 1, I expect it to look like picture 2. It looks like the minimum width for these elements is too large, so instead of being on one row, it puts them in columns.

I made picture 2 by changing the code to repeat(auto-fit, minmax(200px, 1fr));. This is not a great solution as I want the minimum element size to be based on the grid elements' widths, not some arbitrary value.

I do want to have the elements able to be on different rows (for instance, if the browser is very narrow), so CSS grid seems useful for this task. I'm obviously just misunderstanding some key aspect.

Question

What value can I use in my grid-template-columns to make my elements work the way I expect with CSS grid? Is there a way to do it with repeat(auto-fit, X); or do I have to specify the number?

Answer

As stated below, you cannot use repeat(auto-fit with fr as it does not specify an absolute minimum or maximum, which the spec says is invalid. Michael_B gave the answer (in his jdfiddle example comment) of using

  display: flex;
  flex-wrap: wrap;

which does exactly what I expected repeat(auto-fit, 1fr); to do.


Solution

  • This rule won't work.

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

    The problem is explained here: minmax fails (invalid property value)


    This rule won't work:

    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))
    

    The problem is explained here: minmax() defaulting to max