fildred13
fildred13

Reputation: 2350

Hide element "beneath" div of lower z-index

Two fiddles. The first, showing everything working as I want: http://jsfiddle.net/3SWwD

The second, showing the problem as it exists on the site I'm trying to deploy the effect on: http://jsfiddle.net/3SWwD/1/

Those fiddles describe everything this code does, but for thoroughness:

I have two container divs bumped up to one another, the first of which contains an imagel which I have simplified to <div id="image"> for this example.

<div id="container">
    <div id="image"></div>
</div>
<div id="never_cover_me">
</div>

They are styled as follows, and theses styles will exhibit the issue, which I'll explain when I show the js.

#container{
    height: 400px;
    width: 400px;
    background: blue;
    position: relative;
    z-index: 200;
}

#image{
    height: 200px;
    width: 200px;
    background: red;
    position: relative;
    top: 200px;
    left: 100px;
    z-index: 50;
}

#never_cover_me {
    position: relative;
    height: 400px;
    width: 400px;
    background: yellow;
    z-index: 100;
}

Lastly, some Jquery/JS moves the image down, thus into the space of #never_cover_me. If all was well in the world, #image would be covered by #never_cover_me while it was moved down, but since #container has a higher z-index than #never_cover_me, obviously that isn't the case and the image is instead drawn over #never_cover_me.

$(document).ready(function(){
    setInterval(
         function(){
            $('#image').animate({top: '+=200px'}, "slow", function(){
                $('#image').delay(1000).animate({top: '-=200px'}, "slow")
            });
         },3000
    );
});

For various reasons, #container MUST have a higher z-index than #never_cover_me. Semantically, I would prefer if #image stays within #container.

Ideas?

Upvotes: 1

Views: 11177

Answers (2)

user3728283
user3728283

Reputation:

The #container:

z-index: 200;

is above #never_cover_me:

z-index: 100;

Therefore, it is causing the issue you are experiencing. Here is more information on stacking order and how descendants are affected.

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/Stacking_and_float

You shouldn't really try to use other elements to hide your content. A better solution would be to set overflow:hidden; on #container because the effect you are going for is "hide this when the block is outside the current element."

Upvotes: 3

fildred13
fildred13

Reputation: 2350

It was as easy as adding overflow:hidden to #container.

Fiddle: http://jsfiddle.net/3SWwD/2/

Upvotes: 2

Related Questions