简体   繁体   中英

CSS Positioning div on top with z-index

I have a container which has three divs. Each div contains a hidden div which has a 'hide' class ( display:none; ) inside which is supposed to show when hovering on its parent div.

I use toggleClass('show') to which makes the secretDiv display has a block. I need the secretDiv to be shown when hovering on the parent div.

The parent div should show on top of the div below, and not push the other divs

http://jsfiddle.net/2xLMQ/4/

--- HTML ---

<div class="row">
    <div class="element">
        <img src="http://placehold.it/200x100" alt="" title="" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
    <div class="element">
        <img src="http://placehold.it/200x100" alt="my image" title="image title" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
</div>

<div class="row">
    <div class="element">
        <img src="http://placehold.it/200x100" alt="" title="" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
    <div class="element">
        <img src="http://placehold.it/200x100" alt="my image" title="image title" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
</div>

--- CSS ---

.hide {display:none;}
.show {display:block;}
.row {height:160px;background:#dedede;float:left;width:480px;position:relative:z-index:1;}
.row .element {position:relative;z-index:9;text-align:center; float:left; background:#666;width:200px;padding:12px;margin:6px;}
.row .image {}
.row .secretDiv {background:#ff0000;padding:8px;}

--- JS ---

$('.element').hover(function(){
    $('.element .secretDiv').toggleClass('show');
});

First at all change your selector to only match the respective hidden div:

 $('.secretDiv',this).toggleClass('show');

Then add another class on that item to display ontop of the others :

$(this).toggleClass('ontop');

And the class:

.row .ontop {z-index:10;background:orange;}

Check this Demo

Simply add absolute positioning to your 'secret' div:

.row .secretDiv {background:#ff0000;padding:8px; position: absolute; top: 5px; left: 5px;}

Fiddle here: http://jsfiddle.net/moonspace/2xLMQ/12/

As a bonus, I've edited your jQuery to show only the 'secret' div associated with each element:

$('.secretDiv', this).toggleClass('show');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM