Home > Enterprise >  CSS Grid not respecting row and column span rules and placing items in random order
CSS Grid not respecting row and column span rules and placing items in random order

Time:02-02

I'm trying to develop a photo gallery using CSS Grid. I have landscape photos which end with -l.jpeg and portrait photos which end with -p.jpeg.

Phtot Gallery HTML:

<article id="photos">
    <img src="./images/1-l.jpeg">
    <img src="./images/2-l.jpeg">
    <img src="./images/3-l.jpeg">
    <img src="./images/4-l.jpeg">
    <img src="./images/5-l.jpeg">
    <img src="./images/6-p.jpeg">
    <img src="./images/7-p.jpeg">
    <img src="./images/8-l.jpeg">
    <img src="./images/9-p.jpeg">
    <img src="./images/10-l.jpeg">
    <img src="./images/11-p.jpeg">
    <img src="./images/12-l.jpeg">
    <img src="./images/13-p.jpeg">
</article>

Photo Gallery CSS:

img {
    max-width: 100%;
} 

#photos {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-gap: 0.5em;
    grid-auto-flow: row dense;
}

This makes the photo gallery look like:

Uneven Photo Gallery

The photo gallery now has even spaces. To fix that I added the below css,

#photos img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

Zoomed landscape images

But now landscape images are zoomed and not able to view the full wide image. So to fix that, I decided to span portrait images vertically by 2 rows and landscape images horizontally by 2 columns using the below css.

#photos img[src$="-p.jpeg"] {
    grid-row-end: span-2;
}

Now grid looks like,

Portrait Fixed

Now when I add css for landscape images to span 2 columns,

#photos img[src$="-l.jpeg"] {
    grid-column-end: span-2;
}

The grid makes a big uneven space as shown below,

Grid collapsed

Another thing I have noticed is that images are not placed in the expected order as per HTML. Here is the repo link - Afer correcting span syntax

  •  Tags:  
  • Related