Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Z-index on nested absolute elements to overlap similar absolute elements?

Tags:

jquery

css

Here is the fiddle: http://jsfiddle.net/hrQG6/

HTML

<div id='map'>
    <div class='hotspot' id='hs1'>
        <div class='info-window'>
            Foobar
        </div>
    </div>
    <div class='hotspot' id='hs2'>
        <div class='info-window'>
            Foobar
        </div>
    </div>
</div>

CSS

.hotspot {
    position: absolute;
    z-index: 10;
    background-color: blue;
    height: 30px;
    width: 30px;
} 
.info-window {
    display: none;
    height: 250px;
     width: 250px;   
    background-color: green;
    position: absolute;
    z-index: 9999;
}​

The .hotspot elements show in the container. The .info-window elements do not show by default. Clicking a .hotspot will display its corresponding .info-window. However, I want the .info-window to cover any .hotspot elements underneath it.

Instead, .hotspot elements are on top of the .info-window element. Conceptually, I'm misunderstanding the use of position and z-index.

like image 946
Josh Avatar asked Nov 26 '25 14:11

Josh


1 Answers

Your .info-window elements are inside .hotspot elements, both of which have equal z-index. Imagine this:

<div></div>
<div></div>

Since we set the two <div>s with equal z-index values, then they have equal levels. The second, by default, overlaps the first just because of order in the markup.

Now, consider this:

<div><div class="inner"></div></div>
<div><div class="inner"></div></div>

No matter what z-index you give the first .inner element, it will always be underneath the second <div> container, just because of the fact that the first .inner element's <div> container is already underneath the second.

It's like trying to jump as high as you can from the first floor of a building: you'll never get higher than the second floor no matter how high you jump because you'll eventually hit the ceiling, which will prevent you from going any higher.[1]

A better approach would be to use more or less the same markup:

<div class="hotspot">
    <div class="info"></div>
</div>

and use more or less the same CSS rules on .hotspot:

.hotspot {
    position:absolute;
    z-index:10;
}

.hotspot .info {
    display:none;
}

but then, introduce a flag class that overrides that:

.hotspot.active {
    z-index:20; /* let's raise this a bit */
}

.hotspot.active .info {
    display:block;
}

then manipulate that with Javascript:

var hotspots = $('.hotspot').on('click', function (e) {
    hotspots.removeClass('active');
    $(this).addClass('active');
});
like image 69
Richard Neil Ilagan Avatar answered Nov 29 '25 08:11

Richard Neil Ilagan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!