Tip #25: Fix z-index issues using relative positioning

  • — Frontend

  • 2 min. read

  • — 2/23/2023

One of the most annoying things in HTML/CSS is bug-fixing a z-index issue.

Lucky for you, I'll show you an effective trick to fix z-indexing 99% of the time and it's actually really simple.

First, let's look at some markup that has a z-index issue (we'll use an extreme example).

<section class="relative">
  <div>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem eligendi velit eveniet aut. Nihil eveniet voluptate totam repellendus doloribus saepe rerum vitae numquam, commodi alias quo, animi corporis quas laborum!
  </div>
  <div class="absolute inset-0 flex justify-center items-center">
    <div class="rounded-full w-20 h-20 bg-blue-500 "></div>
  </div>
</section>

In this example, we render a blue circle that sits on top of our content (this is bad, we want the blue circle behind our content!).

To fix this, we just need to add relative z-10 to the div that contains our content:

<section class="relative">
  <div class="relative z-10">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem eligendi velit eveniet aut. Nihil eveniet voluptate totam repellendus doloribus saepe rerum vitae numquam, commodi alias quo, animi corporis quas laborum!
  </div>
  <div class="absolute inset-0 flex justify-center items-center">
    <div class="rounded-full w-20 h-20 bg-blue-500 "></div>
  </div>
</section>

There you go, problem solved!

The reason this works is because adding relative and z-10 creates a new stacking context. By default, all CSS elements are using position: static; which actually has no stacking context, thus any other element that's using a position not set to static will cause an overlap.

Using relative here is the safest as opposed to absolute or fixed because relative does nothing to affect the natural flow of the element on the page. In other words, it behaves almost identically to position: static; except that it defines a stacking context (thus you can use z-* to change its z-indexing).

Hopefully this little trick saves you some time trying to fix annoying z-indexing issues!

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!