In this episode, we tackle a pretty common but tricky UI problem: how to properly layer multiple modals so the most recently opened one appears on top. To start, we check out what happens with our current setup — opening one modal from inside another. As you may have noticed, sometimes the new modal ends up underneath the other one, all because of how they're registered in the DOM and the static z-index
we set in CSS.
We dig into how z-index
determines stacking order, and see that simply swapping the component's order in the markup doesn't really solve the problem in a flexible way. We want whatever modal is opened last to always be on top, every single time.
So, what's the fix? Rather than messing around with a global variable or overcomplicating things, we show a handy trick using Alpine.js. The idea is to set each modal's z-index
dynamically, using a value that always keeps increasing, so the most recently opened modal gets the highest z-index
.
We demo a couple of approaches: using timestamps and global counters, but we settle on leveraging JavaScript's performance.now()
, dividing and rounding the result to get a handy number we can use. This rolling value becomes each modal's z-index
when it appears, and it works perfectly – whichever you open last lands on top!
By the end, we’ve got a minimal, elegant solution with no global variables, no event juggling, and no performance concerns — just a bit of clever Alpine code, all wrapped up locally in our modal component.