Home > Net >  Is it possible to use a fixed min and max width for columns in a CSS grid which are repeating and wr
Is it possible to use a fixed min and max width for columns in a CSS grid which are repeating and wr

Time:04-08

I'd like to set up a CSS layout where a container contains a fixed number of flexible width tiles with the following properties:

  • Spacing in between tiles is fixed and consistent
  • They can expand in size between a fixed min and max width, but should all be the same width irrespective of their content. In the example below I'm using 100px min width and 200px max width.
  • They should wrap onto multiple lines if at their minimum width they don't all fit horizontally in the container.
  • If the container is much larger they should not expand larger than their maximum fixed width, should remain centered in the container and the space between them should not expand.

Perhaps it's not possible with pure CSS, but it feels like it should be! There's a minimal example below, which I'll detail here:

Flex and Grid layouts full width

As the container shrinks you can see that the grid layout items are not shrinking with it, but immediately wrap. flex layout behaves nicely:

Flex and Grid layouts container shrinking

As the container continues to shrink, the flex starts to wrap in the desired place, but immediately the tile on the next row expands to its max width:

Flex and Grid layouts container small

CodePudding user response:

In order to achieve what you're trying to do, you'll need to work on both the container and the child.

On the container, you'll set a min-width to 100px and a max that should be the size of the child:

.gridContainer {
  grid-template-columns: repeat(auto-fit, minmax(100px, max-content));
}

And on each child, you'll have a fixed width, but a max-width of 100% so it shrinks if needed:

.child {
  width: 200px;
  max-width: 100%;
}

Updated fiddle: https://jsfiddle.net/7exd5hom/

  • Related