How to make a flexible column with CSS Grid?

I want it to be like this:

2 Columns

When I add another div, it should have 3 Columns like this

But I get this instead when I add a column

When I use grid-column: 1 / -1, it only stacks to a full-width row

When I made the grid-items explicit by using grid-template-columns: 1fr 1fr, grid-column-end: -1 worked but its columns are now hard coded.

2022-09-25-014246_547x276_scrot

Is there a way to have a flexible column in CSS Grid? As of now, I can only hard code a space that a div can take either with grid-column: 1 / span 'N' or grid-template-columns: 1fr 1fr 1fr / repeat(3, 1fr).

Here is the pen.

Have you considered using flex instead of grid?

2 Likes

Grid is the wrong tool for this job as grid is about lining up in 2 dimensions whereas flex is about one dimension.

It’s a cinch in flex. :slight_smile:

I don’t believe its possible in grid because you would need repeat and autofit and the specs don’t allow flexible items into that mix.

From the specs:

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

You could hard code either 2 across or three across of course but not automatically unless you removed the first item into its own one row grid and effectively have 2 grids next to each other. Of course the first item wouldn’t need to be a grid and then you just use grid for your 2 or three across which could be automatic with autofit.

e.g.

However flex is the best bet :wink:

2 Likes

I did consider using flexbox, but I was blinded by the Grid. I’m sorry, everyone. :face_holding_back_tears:

1 Like

You almost said it yourself.

1 Like

Thanks, everyone. I just did it in flexbox. The pen has been updated. Thanks again!

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.