2020-02-29
Specify position property to make Z-index work
tailwind, tailwindcss, css, z-index selfnote
tailwind, tailwindcss, css, z-index selfnote
Image Credit: Commercial Trochus, Commercial Top Shell, Commercial Trochus, Commercial Top Shell
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.
1<nav className="md:hidden">2 <span3 π4 className="z-10 cursor-pointer text-3xl"5 onClick={toggleMenu}6 >7 {isMenuOpen ? "β" : "π"}8 </span>9 {isMenuOpen && <FullMenu />}10</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;
1<nav className="md:hidden">2 <span3 π4 className="z-10 relative cursor-pointer text-3xl"5 onClick={toggleMenu}6 >7 {isMenuOpen ? "β" : "π"}8 </span>9 {isMenuOpen && <FullMenu />}10</nav>
Now the button show up on the top.
https://codesandbox.io/embed/react-hamburger-1-rleky