skip to Main Content

I have the following HTML structure::

<header style="width: 100%; position: fixed; left: 0; z-index:1;">
  <nav style="position: relative;">
    <button style="width: 20px; height: 4px;">
      Open nav
    </button>
    <ul style="width: 100vw; min-height: 100vh; position: absolute; top: 100%; left: 0; z-index: -1;">
      <!-- Some links... -->
    </ul>
  </nav>
</header>
<main>
      <!-- Some content... -->
</main>
<footer>
      <!-- Some content... -->
</footer>

The structure above makes the ul element appear behind the nav element on the z-axis. However, because the nav element’s width is 20px (because this is the width of the button) the ul element appears only behind those 20px and above everything else.

What I am trying to do is to make the ul element appear behind the content in the header element, and above the rest of the content on the page on the z-axis.

For incoming solutions, I would prefer to keep this HTML structure and only change CSS.

Thanks in advance!

2

Answers


  1. Remove position: relative; on nav and position: fixed; on header. Because of both fixed relative they both have different stacking context.
    Read this article to learn more about stacking context.

    Login or Signup to reply.
  2. if you want to implement the z-index for your ul element, it needs to be positioned outside the header element

    Here is what I think you want to achieve:

            <header style="width: 100%; position: fixed; left: 0; z-index: 1;">
                <nav style="position: relative;">
                    <button style="width: 20px; height: 4px;">
                        Open nav
                    </button>
                </nav>
            </header>
    
            <ul style="width: 100vw; min-height: 100vh; position: absolute; top: 100%; left: 0; z-index: -1;">
                <!-- Some links... -->
                <li>Link 1</li>
                <li>Link 2</li>
                <li>Link 3</li>
                <li>Link 4</li>
            </ul>

    Your ul element can be z-index: 0; if you don’t have any other
    element that has such property. So that will be your base stack
    element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search