Recently, I encountered a similar issue and found that the transform: translate3d(0,0,0);
solution did not work for me.
The reason behind this is that z-index only stacks elements in a 2D world. Therefore, when using 3D transformations, z-index does not have any effect.
So, the real question here is:
How can we stack elements in a 3D environment?
The answer is simple:
Use the Z axis!
It may sound straightforward, but it can be confusing due to browser rendering. To illustrate this concept, I created a JSFiddle. In the fiddle, there are four flags arranged in two rows. Additionally, I included two other divs (score) representing an element that should overlay the others. The first row demonstrates a bug, while the second row does not.
To observe the bug, hover your cursor over an element with the CSS properties pointer
on the flag and col-resize
. Notice how the cursor changes when moving over the green element from left to right.
I created some diagrams to clarify the issue. Here, you can see our elements represented as they should be by the browser:
The problem becomes more evident now. On the right side, the green element is above the blue one, which is the desired outcome. However, on the left side, the use of rotateY()
causes the blue element to "leave the screen," overlapping the green element. If this is unclear, visualize the scenario "from above":
We can imagine that the blue element leaves the screen by half its size. My workaround involves translating the blue element along the Z-axis to -10000px to ensure it remains far away and does not overlap with the green element during rotation. The order of operations here is crucial: first, the translation translate3d(0, 0, -10000px)
, followed by the perspective and rotation resulting in:
transform: translate3d(0, 0, -10000px) perspective(1200px) rotateY(-45deg);
. As illustrated in my final diagram from above:
Now, the blue element is distanced enough to avoid going over the green one. However, a potential issue arises if the blue element exceeds 10,000 pixels in size, causing it to overlap once again.
In conclusion, I acknowledge that this solution serves as more of a workaround than a definitive fix. Nonetheless, it proved beneficial in my case, and I hope it assists you in addressing your initial problem without straying too far off track.