CSS Tutorial – CSS Grid of Triangular Shapes


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!

<div class="gallery">
  <img src="https://picsum.photos/id/1040/300/300" alt="a house on the mountain">
  <img src="https://picsum.photos/id/1054/300/300" alt="a big building">
  <img src="https://picsum.photos/id/101/300/300" alt="another house">
  <img src="https://picsum.photos/id/1065/300/300" alt="a small road between two houses">
  <img src="https://picsum.photos/id/1067/300/300" alt="a modern city">
  <img src="https://picsum.photos/id/188/300/300" alt="a lot of old houses">
</div>
.gallery {
  display: grid;
  gap: 10px; 
  grid-template-columns: auto 0 auto;
  place-items: center;
}
.gallery > img {
  width: 200px; /* control the size */
  aspect-ratio: 1;
  object-fit: cover;
  transition: .35s;
  filter: grayscale();
  cursor: pointer;
}
.gallery > img:hover {
  filter: grayscale(0%);
}

.gallery > img:nth-child(1) {
  clip-path: polygon(0 0,50% 0,100% 100%,0 100%);
}
.gallery > img:nth-child(2) {
  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%);
}
.gallery > img:nth-child(4) {
  clip-path: polygon(0 0,100% 0,50% 100%,0 100%);
}
.gallery > img:nth-child(5) {
  clip-path: polygon(50% 0,100% 100%,0% 100%);
}
.gallery > img:nth-child(6) {
  clip-path: polygon(0 0,100% 0,100% 100%,50% 100%);
}

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

You probably know by now that the big trick is figuring out the clip-path to get the shapes we want. For this grid, each element has its own clip-path value whereas the last two grids worked with a consistent shape. So, this time around, it’s like we’re working with a few different triangular shapes that come together to form a rectangular grid of images.

Nandemo Webtools

Leave a Reply