← Go Back

Specify position property to make Z-index work

Broken Post? β†’ Let me know

Just sharing what I learned today.

I was implementing a simple hamburger menu while learning Tailwind.
Clicking on πŸ” (open button) would trigger a full page menu to open and replace the button with ❌ (close button).

The menu shows up but hid the close button.
thus unable to close the menu.

I initially put z-index value set to 10 with z-10 on the menu item.

<nav className="md:hidden">
  <span
                πŸ‘‡
    className="z-10 cursor-pointer text-3xl"
    onClick={toggleMenu}
  >
    {isMenuOpen ? "❌" : "πŸ”"}
  </span>
  {isMenuOpen && <FullMenu />}
</nav>

But the button was still shown under full page menu, <FullMenu />.

I found this article, Z-index not working – troubleshooting after some Googling.

The article states that

The Z-Index property will simply not work if there isn’t a specific positioning for an element that isn’t static

In my case, as fixed/absolute/sticky renders the button elsewhere, I assigned relative position property.

The equivalent CSS would be position: relative;

<nav className="md:hidden">
  <span
                       πŸ‘‡
    className="z-10 relative cursor-pointer text-3xl"
    onClick={toggleMenu}
  >
    {isMenuOpen ? "❌" : "πŸ”"}
  </span>
  {isMenuOpen && <FullMenu />}
</nav>

Now the button show up on the top.


Image Credit: Commercial Trochus, Commercial Top Shell, Commercial Trochus, Commercial Top Shell

Webmentions

Loading counts...

❀️ 0 πŸ’¬ 0
Fetching Replies...
There is no reply...