Fix Any CSS Z-index Issue With This One Trick
(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:
<div class="h-8"></div>
<div class="">
<div class="relative z-20 p-2 text-gray-800 bg-gray-100">
Z-index content (z-index: 20)
</div>
</div>
<div class="h-16"></div>
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;.
<div class="h-8"></div>
<div class="isolate">
<div class="relative z-20 p-2 text-gray-800 bg-gray-100">
Z-index content (z-index: 20)
</div>
</div>
<div class="h-16"></div>
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.
Want to read me more?
-
UI Design Tips Using Tailwind CSS for Developers
Explore some quick tips to level your UI design from okay to great with these Tailwind CSS-based tips. -
The Best of 2024 from Rails Designer (number 1 won't surprise you 🤪)
2024 was the year Rails Designer launched. And an amazing year it was. Let's go over the most popular articles from this year. -
Two products, one Rails codebase
Build multiple products from a single Rails codebase using variants and custom configuration class.
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
{{comment}}