Alan Shortis
Alan Shortis

Reputation: 1109

CSS positioning and z-index

I have been banging my head against this for a while, and despite some googling around and reading I'm reaching the end of my tether.

I have a fixed position header which my content scrolls below. In the header I have a menu icon which opens a menu in an overlay which covers the entire page.

What I want, is for the menu icon to sit above the overlay, the overlay to sit above the header, and the header to sit above everything else.

I have written a fiddle to isolate the issue and hopefully find a solution.

<div class="overlay"></div>
<header> 
    <span>☰</span>
</header>

-

html, body {
    height: 100%;
}
header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    background: rgba(255,0,0,.7);
}
header span {
    float: left;
    margin-left: 20px;
    margin-top: 12px;
    cursor: pointer;
    z-index: 1000;
}
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,255,255,.3);
    z-index: 900;
}

If this is not possible, I am open to suggestions as to a different approach.

http://jsfiddle.net/6d4wj7yt/

Upvotes: 3

Views: 159

Answers (1)

Hashem Qolami
Hashem Qolami

Reputation: 99494

Move the .overlay into the <header> and set give a position other than static to the menu icon.

Example Here

<header> 
    <div class="overlay"></div>
    <span>☰</span>
</header>
header span {
    float: left;
    margin-left: 20px;
    margin-top: 12px;
    cursor: pointer;
    z-index: 1000;
    position: relative; /* <-- added declaration */
}

Explanation

Since the header is positioned absolutely - fixed - it establishes a new stacking context, hence by moving the .overlay into the header, .overlay and the nested span would share the same stacking context.

Besides, z-index is only applicable to non-static positioned elements, therefore you need to give the element a position other than static.

Upvotes: 2

Related Questions