0

I am very new to CSS Grid and would like to use it in my current project for practice. The section in question is a section of cards added in CMS, so I won't know how many items there are, but there will be maximum of 8. I had a look on here for similar questions, but all answers I found suggest adding a class to certain items. I know I can achieve this with Bootstrap, flex box and media queries but I was wondering if there is a neater way with CSS Grid.

What I want to achieve:

  • on mobile: all cards are displayed in one column
  • tablet: two columns
  • desktop: 3 columns, max 3 cards in each row. The gotcha is that if the last row is incomplete - meaning, there is only one card or two cards - it/they should take up maximum 50% of free space.

What I have:

<div class="container">

    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>

</div>
.container {
  display: grid;
  grid-template-columns: repeat(3,1fr);
  grid-gap: 10px;
  padding: 10px;
}

I have seen these questions among others: Take half width in 3 columns CSS grid layout CSS Grid - Number of Columns can be different in the first row than second row

The issue here is that these solutions require me knowing which item is too wide. I would like the "default" width of the child to be 1fr if you will, and stretch to 1.5fr if there is available space.

Is there a way to do this with Grid that is better than Flexbox?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
krzyzws
  • 31
  • 7

0 Answers0