How to use Z-index in TailwindCSS?

In this article, we will dive into TailwindCSS z-index utilities and see why it is so crucial understanding them.

Z-index lets you control and changes the stack order of your elements

Imagine a pile of books inside a case. What if you want to change the order of those books to put the last one in front of the pile? Well, you simply grab it from the pile and put it on top, letting you see the cover of the book.

Now imagine that those books are HTML elements, and the case is the parent element. Z-index utilities let you control the order of those child elements.

Let's take a real code example:

In this example, because we didn't change any of the z-index elements, the child element with the pink background (bg-pink-500) will be the element on the top of the stack.

  <section class="h-96 flex flex-col bg-gray-100 justify-center items-center">
    <!-- Childs -->
    <div class="absolute w-48 h-48 rounded-lg bg-green-500"></div>
    <div class="absolute w-48 h-48 rounded-lg bg-blue-500"></div>
    <div class="absolute w-48 h-48 rounded-lg bg-yellow-500"></div>
    <div class="absolute w-48 h-48 rounded-lg bg-purple-500"></div>
    <!-- This element will be on top -->
    <div class="absolute transform -translate-x-4 w-48 h-48 rounded-lg bg-pink-500"></div>
  </section>

z-index fig 1.png

But what if we want to put the child element with the green background (bg-green-500) on top of the stack? Well, we can add a TailwindCSS Z-index utility into the element's class.

In this example, we will add z-50.

  <!-- PARENT -->
  <section class="h-96 w-screen flex bg-gray-100 justify-center items-center">
    <!-- Childs -->
    <!-- This element will be on top -->
    <div class="z-50 absolute w-48 h-48 rounded-lg bg-green-500"></div>
    <div class="absolute w-48 h-48 rounded-lg bg-blue-500"></div>
    <div class="absolute w-48 h-48 rounded-lg bg-yellow-500"></div>
    <div class="absolute w-48 h-48 rounded-lg bg-purple-500"></div>
    <div class="absolute transform -translate-x-4 w-48 h-48 rounded-lg bg-pink-500"></div>
  </section>

z-index fig2.png

👉 You can play with this example on Tailwind Play.

Out-of-the-box you have access to 6 levels of depth, from z-0 (the lowest level) to z-50 (the top-level) and one auto utility (z-auto). You can also create, change, or delete any of them by editing the theme.zIndex section in your TailwindCSS config file.

z-index fig3.png

z-index and responsiveness

This utility is available out of the box with the {screen}: prefix. This allows you to change the z-index when a breakpoint is reached.

<div class="z-50 md:z-0">My z-index will change</div>

z-index fig4.png

No Comments Yet