I am creating a CSS grid that displays the photos of the guests in my podcast.
For my particular case, the grid will assume:
- There is a minimum of 1 guest
- There is a maximum of 4 guests
- The photo images are all square (ex 100px x 100px)
The basic structure of the HTML looks like this:
<div class="cards">
<img src="/guests/guest1.png" alt="" class="card" class="card">
<img src="/guests/guest2.png" alt="" class="card" class="card">
<img src="/guests/guest3.png" alt="" class="card" class="card">
<img src="/guests/guest4.png" alt="" class="card" class="card">
</div>
I want the guests to display within a CSS grid container.
Note: I do not want the images to look stretched, so I use object-fit: cover (but that is not the issue, I do not think)
.cards {
display: grid;
grid-template-columns: repeat(2, minmax(50%, 100%));
gap: 2px;
width: 110px;
height: 110px;
}
.card {
width: 100%;
object-fit: cover;
}
The rules I want to set are as follows:
- For 4 guests, display 4 boxes with 2 rows and 2 columns. This works!
- For 3 guests, display 3 boxes with 2 rows and 2 columns and do not stretch the guest across the entire second row. This works!
- For 2 guests, display 1 row and 2 columns at a 50% width for each image. This does not work :-(
- For 1 guest, display 1 row and 1 column at 100% width for the full image. This does not work :-(
As you can see in the screenshot, The grid does not display as I would hope for 2 guests or 1 guest.
Perhaps CSS Grid is the wrong choice or maybe I am missing something?
Ideally, I do not want to use JavaScript, but scss mixins would be okay (which may be a choice here?), but I would like to know if I can do this purely with CSS Grid or maybe Flexbox(?). If it helps any, I am using Jekyll with the Liquid language.
Is there a way I can create a CSS Grid that properly displays the photos so they are the correct size based on the number of images displayed?