0

What I'm trying to do is placing the <button> element on top of the <div> element and, at the same time, place the <nav> behind the <div>. In other words, anything but the <button> should be visible.

Demo: https://play.tailwindcss.com/DW91IdO9dL

  1. A sticky <nav> element with position: sticky
  2. The <nav> has a <button> child with position: relative; z-index: 30
  3. A <div> element with position: fixed; z-index: 20

Of course, this isn't working, <button> isn't visible at all, despite the greater z-index. I guess because the <nav> crate a new stacking context. Setting a z-index: 30 on the <nav> itself would show the <button>, but also other <nav> elements and its background color:

fixed position issue

This is the HTML structure, but I can change as I wish (place the <div> before/after):

<nav style="position: sticky">
  <button style="position: relative; z-index: 30"></button>
</nav>

<div style="position: fixed: z-index: 20"></div>
gremo
  • 47,186
  • 75
  • 257
  • 421
  • This won't work, because children inherit the stacking order of their parents - see [https://stackoverflow.com/questions/51991878/z-index-not-working-as-expected-text-showing-under-blocks] – biberman Jun 15 '22 at 11:42
  • read until the end of the duplicate to find ideas of solution – Temani Afif Jun 15 '22 at 13:56

1 Answers1

0

What you're trying to do isn't possible. What I would suggest is to have the nav set with no background color or z-index. Add another div to your nav and use that as a background color. You can then set the z-index of every element in the nav set lower than the div. But set the button's index higher.

Edit: Here's a working example: https://codepen.io/kenjibailly/pen/wvyNYqx

HTML: ✕

<div></div>

CSS:

nav {
  width: 100%;
  position: relative;
  background: white;
}

nav > div:last-child {
  background: white;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

nav > div {
  width: 100px;
  height: 20px;
  background: green;
  margin-top: 5px;
}

button {
  color: white;
  position: relative;
  z-index: 3;
  background: red;
}

nav + div {
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: blue;
}

This has already been answered here in a different but similar context: can I override z-index inheritance from parent element?

Kenji Bailly
  • 107
  • 9
  • Won't work. Removed z-index from nav, set z-index 30 on button... and other elements to a lower z-index. – gremo Jun 15 '22 at 12:05
  • @gremo I added a working example in my answer above. – Kenji Bailly Jun 15 '22 at 22:53
  • Thanks, but still need a z-index for the nav. The concept is: nav is above body (say z-index: 10), div is above nav (say z-index: 20). Button inside nav should be above div. Isn't that possible, right? – gremo Jun 16 '22 at 14:32
  • @gremo That's not possible as the button will be relative to the nav's z-index. – Kenji Bailly Jun 16 '22 at 15:47