I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Right now, I am using JavaScript to achieve this by setting the offset based on the triangle's index within the parent container. However, it feels like a workaround and I am exploring if there is a way to accomplish this purely with CSS. I wonder if there might be a CSS feature that allows me to access each triangle div’s index or if there is an alternative method in CSS to achieve the same result.
let triangleRows = [...document.getElementsByClassName('triangle-row')]
triangleRows.forEach(row => {
let children = [...row.children]
// set each triangle's --tri-index variable to its index
children.forEach((tri, idx) => tri.style.setProperty('--tri-index', idx))
})
:root {
--tri-width: 5rem;
--tri-ratio: 0.86603;
--offset: -2.25rem
}
.triangle-row {
display: flex;
margin-top: 0.2rem;
}
.triangle {
position: relative;
height: calc(var(--tri-width) * var(--tri-ratio));
width: var(--tri-width);
left: calc(var(--offset) * var(--tri-index));
background-color: red;
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
.triangle:hover {
background-color: yellow;
}
.flipped {
clip-path: polygon(0% 0%, 50% 100%, 100% 0%);
}
<div class="triangle-row">
<div class="triangle"></div>
<div class="triangle flipped"></div>
<div class="triangle"></div>
<div class="triangle flipped"></div>
<div class="triangle"></div>
</div>
<div class="triangle-row">
<div class="triangle flipped"></div>
<div class="triangle"></div>
<div class="triangle flipped"></div>
<div class="triangle"></div>
<div class="triangle flipped"></div>
</div>