Skip to content

[css-grid] Request: an easy way to set adjusted-to-fit repeated track sizes #3767

Open
@AmeliaBR

Description

@AmeliaBR

I'd like an easy & intuitive way to specify the following grid layout pattern:
Set an ideal track size (column width or row height), and then have automatic repeats where the actual track size are adjusted to neatly fit the container, without overflowing or leaving gaps.

In other words, I want column widths that are the same as I'd get for a multi-col layout with:

column-width: <length>;

(I'm using columns in the example for comparison to multi-col, but of course this should also work for auto-repeat rows when the block size of the container is constrained.)

You can get almost all the way there, currently, by saying for your grid container:

grid-template-columns: repeat(auto-fit, minmax(<length>, 1fr));
/* determine the number of columns at the specified min length,
    then stretch all the columns to equal width to fill the available space */

...but that forces the <length> to be treated as a strict minimum track size, causing overflow if the container width is smaller than that. To override the minimum, you either need to wrap the minmax() function in a min() function (when that is eventually supported cross-browser) or use a media query (assuming the container width that triggers overflow can be reliably calculated from the document width).

With a min() constraint added, you're looking at the following CSS:

grid-template-columns: repeat(auto-fit, min(minmax(<length>, 1fr), 100%));

which is:

  • a lot to type compared to the multi-col version.
  • not very intuitive.
  • easy to mess up.

Some potential syntaxes for making that long, complex command simpler:

grid-template-columns: repeat(auto-fit-round, <length>);
grid-template-columns: repeat(auto-fill-round, <length>);
  /* but round as used elsewhere in CSS repeats (round up or down to even integer)
     is different from the multi-col behavior (length is min unless it causes overflow) */

grid-template-columns: repeat(auto-fit-flex, <length>);
grid-template-columns: repeat(auto-fill-flex, <length>);
  /* but would calling it flex make devs think they could control it
      with flex-grow and -shrink properties? Or is it close enough to fr? */

grid-template-columns: repeat(<length>);
  /* short & sweet, but we'd have to decide if this expands 
      to an auto-fit or auto-fill version, re collapsing empty tracks */

PS, If you think there is existing CSS that can handle this more simply, please give it a go:

More examples/discussion courtesy of Amber Weinberg-Jones's tweet:
https://mobile.twitter.com/amberweinberg/status/1110584873167785985

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions