Search code examples
csscss-gridclip-path

Grid layout & clip-path help (disappearing middle image)


I'm am currently exploring clip-path. I'm having some trouble with a grid layout and disappearing image.

I have three images in a div called .gallery. I want them to:

  • Display next to each other within their clip-path.
  • Maintain a 10px spacing between them.
  • Respond to screen size by shrinking proportionally but keeping their formation.

.gallery {
  display: grid;
  gap: 10px;
  box-sizing: border-box;
  grid-template-columns: auto 0 auto;
  place-items: center;
}

.gallery>img {
  max-width: 100%;
  aspect-ratio: 1;
  object-fit: cover;
}

.gallery>img:nth-child(1) {
  clip-path: polygon(0 0, 50% 0, 100% 100%, 0 100%);
}

.gallery>img:nth-child(2) {
  /\* Clip-path for the middle image \*/ clip-path: polygon(0 0, 100% 0, 50% 100%);
}

.gallery>img:nth-child(3) {
  clip-path: polygon(50% 0, 100% 0, 100% 100%, 0 100%);
}

@media (max-width: 610px) {
  .gallery>img {
    width: 100%;
  }
  .gallery {
    grid-template-columns: auto auto auto;
  }
}
<div class="gallery">
  <img SRC="https://dummyimage.com/600x400/000/fff&text=one">
  <img SRC="https://dummyimage.com/600x400/000/fff&text=two">
  <img SRC="https://dummyimage.com/600x400/000/fff&text=three">
</div>

The middle image disappears when using grid-template-columns: auto 0 auto; for responsiveness. I've tried changing it to auto auto auto in the media query, and although that does prevent the image from disappearing, the gap between the images is larger than 10px.

Can anyone point me in the right direction to fix the disappearing image and achieve the desired layout with consistent spacing?

grid-template-columns: auto 0 auto Image with styles grid-template-columns: auto 0 auto applied

grid-template-columns: auto auto auto image with applied style grid-template-columns: auto auto auto


Solution

  • I would do it like below and I advice you to read my article: https://css-tricks.com/css-grid-and-custom-shapes-part-3/

    .gallery {
      --s: 100px; /* control the clip-path and the size of the middle image */ 
    
      display: flex;
      gap: 10px; /* the gap */
      height: 200px; /* the image height */
    }
    
    .gallery > img {
      min-width: 0;
      object-fit: cover;
    }
    
    .gallery > img:nth-child(1) {
      flex: 1;
      clip-path: polygon(0 0,calc(100% - var(--s)) 0,100% 100%,0 100%);
    }
    
    .gallery > img:nth-child(2) {
      clip-path: polygon(0 0,100% 0,50% 100%);
      width: calc(2*var(--s));
      margin-inline: calc(-1*var(--s));
    }
    
    .gallery > img:nth-child(3) {
      flex: 1;
      clip-path: polygon(var(--s) 0, 100% 0, 100% 100%, 0 100%);
    }
    <div class="gallery">
      <img src="https://picsum.photos/id/28/800/400">
      <img src="https://picsum.photos/id/174/800/400">
      <img src="https://picsum.photos/id/188/800/400">
    </div>