Direction Aware Tiles Pure CSS – How It Works

Introduction

After my previous work where I used two HTML elements to determine which side the card will flip, I’ve decided to use four this time. The four elements will detect the top, right, bottom, and left sides respectively. This means each box will now be able to flip horizontally or vertically depending on where you approach it using the mouse cursor.

How it works

There are four <a> tags before each .box div and those tags are the ones that determine which side the box/square will flip. Here’s an illustration of what the <a> tags look like when I added a black background color to each one.

Direction Aware Image 001

You will notice that they are triangles and that is so that they don’t overlap with each other. I used the clip-path CSS property to create the shapes. Now, when the cursor hovers over the first <a> tag, the corresponding CSS code below will run:

.col a:nth-child(1):hover ~ .box {
transform: rotateX(180deg);
}

This will cause .box or the square to flip upwards. Because of the general sibling combinator ~ (tilde), I am able to rotate the square 180 degrees on the X-axis. By copying and modifying this CSS line for the other <a> tags, I can rotate to the Y-axis too.

.col a:nth-child(2):hover ~ .box {
transform: rotateY(180deg);
}
.col a:nth-child(3):hover ~ .box {
transform: rotateX(-180deg);
}
.col a:nth-child(4):hover ~ .box {
transform: rotateY(-180deg);
}

Covering all bases

Alright, so there is one more important thing we need to do. When hovering on a triangle or <a> tag, we need to set its clip-path to ‘none’ and increase its z-index value so that the triangle turns into a square shape to cover and overlap the rest of the other triangles. The reason for this is so that your mouse cursor can move freely inside without triggering another flip.

.col a:hover {
z-index: 3;
-webkit-clip-path: none;
clip-path: none;
}

The moment your cursor leaves the square (a.k.a. un-hover), the clip-path and z-index properties will reset, turning the square back into a triangle, and afterwards, the .box div will then flip back to its original state.

You can find the full source code at CodePen. Feel free to copy and play with it yourself.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.