Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use Tailwind Z index to Control Stack Order

Controlling stacking order is an essential yet often overlooked aspect of web design. However, the powerful z-index property allows you to precisely layer elements on top of one another, creating depth and visual intrigue.

In this article, we will explore the z-index tool in Tailwind CSS. You will learn insider techniques to control stack order with utility classes, unlocking new dimensions of layered layout possibility.

We will stack menus, modals, backdrops, and more in the course of this article. You will gain best practices to avoid surprises, keep values consistent, and elegantly handle responsiveness.

By the end, you will have mastered the art of web element layering with Tailwind CSS z-index. Let’s float gently into this third dimension of Tailwind CSS!

What is the z-index Property in CSS?

The z-index property in CSS is a great tool that helps you control the vertical stacking order of elements that overlap. It is like a third dimension to your 2D webpage layout, allowing you to layer elements on top of each other, much like how you would stack a deck of cards.

How z-index Property Controls Stack Order

The z-index property assigns a stack level to an HTML element. Elements with a higher stack level are rendered in front of elements with a lower stack level. The default z-index value for all elements is auto, which corresponds to a stack level of 0.

Here is a simple z index example with CSS:

#div1 {
  background: lightcoral;
  left: 60px;
  top: 60px;
  z-index: 1;
  position: absolute;
  width: 300px;
  height: 100px;
}

#div2 {
  background: lightblue;
  left: 80px;
  top: 80px;
  z-index: 2;
  position: absolute;
  width: 300px;
  height: 100px;
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <div id="div1"></div>
    <div id="div2"></div>
  </body>
</html>

In this example, #div2 appears on top of #div1 because it has a higher z-index value.

Check out another Tailwind CSS utility class for controlling stacking context in this video below:

Importance of Layered Layouts

The z-index property is crucial for creating layered layouts, where some elements need to be displayed on top of others. For instance, a dropdown menu to appear on top of other page content when it is open, or a modal dialog to be displayed in front of the main page.

Without the z-index property, elements would stack in the order they appear in the HTML source code, which might not always give the desired result. With z-index, you have full control over this stacking order.

Here is a simple example using Tailwind CSS:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <div class="relative">
      <div class="absolute z-10 bg-red-300">I'm on top!</div>
      <div class="absolute z-0 bg-green-300">I'm at the bottom!</div>
    </div>
  </body>
</html>

In our illustration above, the red div appears on top of the green one, thanks to the z-index classes provided by Tailwind CSS. This demonstrates the power and flexibility of the z-index property in creating complex, layered layouts.

z-index Utilities in Tailwind CSS

Tailwind CSS provides a set of utility classes for controlling the z-index of an element. These utilities make it easy to change the stack order of elements directly in your HTML, without having to write custom CSS.

Format for the z-index Utility Classes

The format for the z-index utility classes in Tailwind CSS is z-{value}. The {value} can be a number from 0 to 50 or auto. For example, z-10 sets the z-index of an element to 10, while z-auto sets it to auto. Below is a table of the classes and the properties they correspond to, including z auto and more:

z-index: 0; z-10	z-index: 10; z-20	z-index: 20; z-30	z-index: 30; z-40	z-index: 40; z-50	z-index: 50; z-auto	z-index: auto;

Use Cases of Z-Index

The z-index utilities in Tailwind CSS can be used in a variety of scenarios where you need precise control over the stack order of elements. Here are a few examples:

  • Element Overlapping: If you have elements that overlap, such as dropdown menus or modal dialogs, you can use the z-index utilities to control which element appears on top.

  • Creating Depth and Visual Harmony: You can use the z-index utilities to create a sense of depth in your designs, by layering elements at different z-index levels. This can help to create a more visually appealing layout.

Here is an example of how you might use the z-index utilities in Tailwind CSS to create a layered layout:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <div class="relative">
      <div class="absolute z-20 bg-blue-500 p-2">I'm on top!</div>
      <div class="absolute top-6 z-10 bg-red-500 p-2">I'm in the middle!</div>
      <div class="absolute left-8 top-2 z-0 bg-green-500 p-2">
        I'm at the bottom!
      </div>
    </div>
  </body>
</html>

In this example, the blue div appears on top, the red one in the middle, and the green one at the bottom. This is because they have been assigned z-index values of 20, 10, and 0 respectively.

Sticky Elements with Z-Index

In web design, sticky elements are those that stick to the top of the viewport when you scroll down. They’re commonly used for navigation bars, headers, or any other element that you want to keep visible at all times. Tailwind CSS provides a utility for creating sticky elements, and it works hand in hand with the z-index property.

The sticky class in Tailwind CSS applies a position: sticky style to an element, which makes it “stick” to the top of the viewport when you scroll down. However, the sticky element will only “stick” inside its parent element, and will stop being sticky once its parent is no longer in view.

Here is an example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <div>
      <div>
        <div class="sticky top-0 bg-blue-200 p-2">A</div>
        <div>
          <!-- Content goes here -->
        </div>
      </div>
      <div>
        <div class="sticky top-0 bg-blue-200 p-2">B</div>
        <div>
          <!-- Content goes here -->
        </div>
      </div>
      <div>
        <div class="sticky top-0 bg-blue-200 p-2">C</div>
        <div>
          <!-- Content goes here -->
        </div>
      </div>
    </div>
  </body>
</html>

In this example, the divs stick to the top of the viewport when you scroll down until its parent div is no longer in view. The top-0 class is used to specify where the element should stick, and the z-10 class ensures that it appears on top of any other content.

Usage of Navigation Bars

Another common use case for sticky elements is navigation bars. By making a navigation bar sticky, you can ensure that it is always accessible to the user, no matter how far down they scroll.

Here is an example of a sticky navigation bar using Tailwind CSS:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <nav class="bg-gray-800 text-white px-4 py-2 sticky top-0 z-100">
      <div class="container mx-auto flex justify-between items-center">
        <a href="#" class="text-xl font-bold">My App</a>
        <ul class="flex space-x-6">
          <li><a href="#" class="hover:text-gray-300">Home</a></li>
          <li><a href="#" class="hover:text-gray-300">About</a></li>
          <li><a href="#" class="hover:text-gray-300">Contact</a></li>
        </ul>
      </div>
    </nav>
    <!-- Content goes here -->
  </body>
</html>

In this example, the navigation bar sticks to the top of the viewport and will always appear on top of any other content, thanks to the high z-index value.

Modals Overlays and Z-Index

Modal overlays are a common feature in many web applications. They are used to display additional content or interactive elements on top of the main page content, often in response to user actions such as clicking a button. The z-index property plays a crucial role in ensuring that these overlays appear on top of all other content.

High z-index for Modal Overlays

Modal overlays typically have a high z-index value to ensure that they appear on top of all other page content. This prevents any other elements from interfering with the modal overlay while it is open.

Here is an example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <!-- Content goes here -->
    <div class="fixed inset-0 z-50 flex items-center justify-center">
      <div class="bg-blue-100 p-6 rounded shadow-2xl">I'm a modal overlay!</div>
    </div>
  </body>
</html>

In this example, the modal overlay is positioned on top of all other content, thanks to the z-50 class. The fixed and inset-0 classes ensure that the overlay is positioned appropriately within the viewport.

Backdrop Element

Often, modal overlays are accompanied by a backdrop element, which is a semi-transparent layer that covers the entire page behind the modal. This helps to focus the user’s attention on the modal content. The backdrop also typically has a high z-index value, but lower than the modal itself, to ensure that it appears behind the modal but in front of all other content.

Here is an example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <div class="fixed inset-0 bg-black bg-opacity-50 z-40"></div>
    <!-- Content goes here -->
    <div class="fixed inset-0 z-50 flex items-center justify-center">
      <div class="bg-blue-100 p-6 rounded shadow-2xl">I'm a modal overlay!</div>
    </div>
  </body>
</html>

In this example, the backdrop is created using a div with a fixed position, inset-0 to cover the entire viewport, bg-black bg-opacity-50 to make it semi-transparent, and z-40 to place it behind the modal overlay but in front of all other content.

Customizing z-index Values

While Tailwind CSS provides a range of z-index utility classes out of the box, there may be times when you need to customize these values to suit your specific needs. Tailwind makes this easy with its configuration file.

Negative Z Index Value

To use a negative z-index value in Tailwind CSS, you can prefix the class name with a dash. For example, Tailwind will generate a class like -z-10 when it sees a leading dash, this will automatically mean that the z index will be a negative value.

Tailwind Config File (tailwind.config.js)

The tailwind.config.js file is where you can customize various aspects of Tailwind CSS, including z-index values. This file is created when you initialize Tailwind CSS in your project.

Modifying z-index Layers

To customize the z-index layers, you can modify the zIndex key in the theme section of the tailwind.config.js file. By default, this key is set to a range of values from 0 to 50, plus auto.

Here is what it looks like by default:

module.exports = {
  theme: {
    zIndex: {
      '0': 0,
      '10': 10,
      '20': 20,
      '30': 30,
      '40': 40,
      '50': 50,
      'auto': 'auto',
    },
  },
  // ...
}

Add Custom Values

To add a custom z-index value, simply add a new key-value pair to the zIndex object. The key should be a string that you will use in your utility classes, and the value should be the z-index value you want to assign.

Here is an example where we add a custom z-index value of 100:

module.exports = {
  theme: {
    zIndex: {
      '0': 0,
      '10': 10,
      '20': 20,
      '30': 30,
      '40': 40,
      '50': 50,
      '100': 100, // our custom value
      'auto': 'auto',
    },
  },
  // ...
}

In this example, you can now use z-100 in your HTML to assign a z-index of 100 to an element.

Best Practices

When working with the z-index property in Tailwind CSS, there are a few best practices that can help you avoid common pitfalls and keep your code maintainable.

Keeping z-index Values Consistent

It is important to keep your z-index values consistent across your project. This means using the same z-index value for the same type of element across different components or pages. For example, if you use z-10 for dropdown menus, make sure to use z-10 for all dropdown menus across your project. This helps to prevent unexpected stacking issues.

Avoiding Unnecessary Complexity

While it can be tempting to use high z-index values to ensure an element always appears on top, this can lead to unnecessary complexity and potential issues down the line. It is generally best to keep your z-index values as low as possible, and only increase them when necessary.

Comments for Clarifying Values

Suppose you’re using a z-index value that might not be immediately obvious to other developers (or even to future you). In that case, it can be helpful to add a comment explaining why you chose that value. This can save a lot of time and confusion later on.

Here is an example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <div class="z-50">
      <!-- z-50 because this needs to be on top of everything else -->
      I'm a modal overlay!
    </div>
  </body>
</html>

Responsive Adjustment

Remember that Tailwind CSS allows for responsive design, which means you can adjust the z-index value based on the viewport size. This can be useful in scenarios where the stacking order of elements needs to change at different screen sizes.

Here is an example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Responsive Adjustment</title>
  </head>

  <body>
    <div class="relative">
      <div class="absolute bg-blue-500 p-2 md:z-20">
        I'm on top of medium screens and above!
      </div>
      <div class="absolute top-8 z-10 bg-red-500 p-2">I'm in the middle!</div>
      <div class="absolute left-20 top-5 z-0 bg-green-500 p-2">
        I'm at the bottom!
      </div>
    </div>
  </body>
</html>

By following these best practices, you can ensure that your use of the z-index property in Tailwind CSS is effective, maintainable, and less prone to bugs.

Wrapping Up

Controlling element stacking order is an essential yet often overlooked aspect of web design. However, as you’ve seen in this article, the powerful z-index property exists precisely for this purpose.

We explored the z-index utilities in Tailwind CSS which provide an easy way to control stack order right in your HTML. You learned how to layer menus, modals, backdrops, and more using these utility classes.

You now have the skills to create depth and visual intrigue by precisely positioning elements in that “third dimension” of the web page. By keeping z-index values consistent, adding comments, and responsively adjusting as needed, you can avoid surprises and elegantly handle complex interfaces.

Congratulations on mastering element layering with Tailwind CSS z-index! You’re now prepared to float gently into this exciting dimension of web design.

You can also check out this video:

Level Up Your Tailwind CSS Skills with Purecode

Purecode.ai is a marketplace library boasting a collection of over 10,000 custom AI-generated components of Tailwind CSS, CSS3, and MUI. It is a great resource for finding pre-made components that you can use in your projects, saving you time and effort in creating responsive designs.

Check out Purecode today to explore their vast collection of Tailwind CSS components and give your next project a boost!

Further Readings

If you enjoyed reading this piece, I bet you will find the following articles on Purecode.ai Blog worth reading:

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.