CSS Tutorial – CSS Grid of Puzzle Pieces


Rengga Dev – This time, I want to dive into another type of grid, one that works with shapes.

Like, what if the images aren’t perfectly square but instead are shaped like hexagons or rhombuses? Spoiler alert: we can do it. In fact, we’re going to combine CSS Grid techniques we’ve looked at and drop in some CSS clip-path and mask magic to create fancy grids of images for just about any shape you can imagine!

This time we are going to play with the CSS mask property to make the images look like pieces of a puzzle.

.gallery {
  --s: 200px; /* control the size */
  --g: 6px;   /* control the gap */
  --r: 42px;  /* control the circular shapes */
  
  display: grid;
  gap: var(--g);
  grid: auto-flow var(--s)/repeat(2,var(--s));
}
.gallery > img {
  object-fit: cover;
  -webkit-mask: var(--_m);
          mask: var(--_m);
}
.gallery > img:is(:nth-child(1),:nth-child(4)) {
  width: 100%;
  height: calc(100% + var(--r));
}
.gallery > img:is(:nth-child(2),:nth-child(3)) {
  height: 100%;
  width: calc(100% + var(--r));
}
.gallery > img:nth-child(1) {
  --_m: 
    radial-gradient(calc(var(--r) + var(--g)) at calc(100% + var(--g)) 50%,#0000 95%,#000) 
      top/100% calc(100% - var(--r)) no-repeat, 
    radial-gradient(var(--r) at left 50% bottom var(--r),#000 95%,#0000);
}
.gallery > img:nth-child(2) {
  place-self: end;
  --_m: 
    radial-gradient(calc(var(--r) + var(--g)) at 50% calc(100% + var(--g)),#0000 95%,#000) 
      right/calc(100% - var(--r)) 100% no-repeat, 
    radial-gradient(var(--r) at top 50% left var(--r),#000 95%,#0000);
}
.gallery > img:nth-child(3) {
  --_m: 
    radial-gradient(calc(var(--r) + var(--g)) at 50% calc(0% - var(--g)),#0000 95%,#000) 
      left/calc(100% - var(--r)) 100% no-repeat, 
    radial-gradient(var(--r) at top 50% right var(--r),#000 95%,#0000);
}
.gallery > img:nth-child(4) {
  place-self: end;
  --_m: 
    radial-gradient(calc(var(--r) + var(--g)) at calc(0% - var(--g)) 50%,#0000 95%,#000) 
      bottom/100% calc(100% - var(--r)) no-repeat, 
    radial-gradient(var(--r) at left 50% top var(--r),#000 95%,#0000);
}

body {
  margin: 0;
  min-height: 100vh;
  display: grid;
  place-content: center;
  background: #ECD078;
}

Here is another example where I am using a conic gradient instead of a radial gradient. This gives us triangular puzzle pieces while keeping the same underlying HTML and CSS.
A last one! This time I am using clip-path and since it’s a property we can animate, we get a cool hover by simply updating the custom property that controls the shape.

Nandemo Webtools

Leave a Reply