🎉 Black Friday/Cyber Monday Deal: get 30% off 🎉

Fix Any CSS Z-index Issue With This One Trick

Published at (last updated at ) Leave your comment

(apologies in advance for the title… 😉)

Z-index controls the stacking order of elements, to determine which elements appear on top of others in the visual layout. It allows you to create interesting UI’s and visual designs by creating depth (literally).

But create web-apps or sites for long enough and soon you come across a z-index issue. Over the years I’ve explored and used many techniques to battle them. From z-index maps (back in the SCSS days) to throwing in the towel and just adding z-index: 99999. (╯°□°)╯︵ ┻━┻

Let’s look at a common example.

<nav class="sticky top-0 z-10">
  Sticky Nav (z-index: 10)
</nav>

<div class="">
  <div class="relative z-20">
    Z-index content (z-index: 20)
  </div>
</div>

The Z-index content will scroll “on top” of the nav element. See this preview:

Z-index content (z-index: 20)

You might think to just change the nav’s z-index to 30 and call it a day. But we both know it’s not going to end well. 😉

The modern (and way more sane) way is to use the isolation property.

<nav class="sticky top-0 z-10">
  Sticky Nav (z-index: 10)
</nav>

<div class="isolate">
  <div class="relative z-20">
    Z-index content (z-index: 20)
  </div>
</div>

This is using Tailwind CSS, but all you need to know is that the isolate class is the same as isolation: isolate;.

Z-index content (z-index: 20)

Once you learn about isolation: isolate; you see many other use cases for it in your apps.

Explore this article for more design tips for developers.

💬 Over to you…

What did you like about this article? Learned something knew? Found something is missing or even broken? 🫣 Let me (and others) know!

Comments are powered by Chirp Form

More articles like this on modern Rails & frontend? Get them first in your inbox.
JavaScript for Rails Developers
Make JS your 2nd favorite language