ponktoku.dev

(CSS) z-index

Explore the CSS z-index property

・ 2 min read
Last updated:

CSS z-index is a property used to control the stacking order of positioned elements in the HTML document. An element with greater stack order is always in front of an element with a lower stack order.

# CSS
img {
	z-index: -1;
}
 
# Tailwindcss
<img class="z-50" />

DocumentationSection titled Documentation

My use caseSection titled My%20use%20case

In the process of building my portfolio website I stumbled upon a case where images for my Article/Post Card components were going on top of the navigation bar. I thought it might be an issue with the relative positioning I used in the styling of the card but that was not the case.

Images of the problemSection titled Images%20of%20the%20problem

Article card overlapping with navigation bar

Article card overlapping with dropdown menu

The solution (using z-index)Section titled The%20solution%20(using%20z-index)

The solution was to use the z-index css property, which when put on elements determines what element goes on top. So I added a z-index of 50 with tailwind (z-50) onto the navigation bar. Since normal elements have a z-index of 0 elements go underneath the sticky navigation bar.

TLDR:

  • All elements start with a z-index of 0.
  • The higher the z-index the higher the element is on the page.
  • You can set negative z-indexes.

Example: 2 squares one has z-index of 1 and the other has z-index of 2. The z-index 2 square is the one that appears on top if there ever is any overlap on the page.

Fixing overlapping elements with css z-index property