MeltingDog
MeltingDog

Reputation: 15458

CSS: Stack dynamically sized divs on top of each other (using z-index)

I have a series of divs with dynamic content inside (length of content determined by CMS):

<div class="contentbox">
~content~
</div>
<div class="contentbox">
~content~
</div>
<div class="contentbox">
~content~
</div>

I want the top of each of these divs to sit just under the one on top, creating a '3D stack of paper' effect.

Normally I would use z-indexes and position absolute and just set the margin-top to the height of the parent div, eg:

#contentbox1 {
height: 300px;
z-index:99;
position: absolute;
}
#contentbox2 {
margin-top: 290px;
height: 300px;
z-index:98;
position: absolute;
}

But this wont work if I have dynamic content and dont know what the height of the div above will be.

Does anyone know of a way to go about this so I can "3D stack" the divs and but position them further down the page?

EDIT: Here is a fiddle of my issue: http://jsfiddle.net/XHJS8/2/ (note how you cannot see the other 2 divs as they are hidden by the larger first one)

Upvotes: 0

Views: 1006

Answers (1)

MeltingDog
MeltingDog

Reputation: 15458

OK, the only way I could really do it was with JQuery: http://jsfiddle.net/XHJS8/8/

Here I am getting the height of the previous div and adjusting the current divs margin-top accordingly:

var num = $('.contentbox').length;

var i = 0;

var z = 99;

var totalmarg = 0;

while(i <= num){

    if (i > 1){
        y = i - 1;

       var margheight = $(".contentbox:nth-child(" + y + ")").height();

        margheight = margheight + 20;

        totalmarg = totalmarg + margheight;

        $(".contentbox:nth-child(" + i + ")").css("margin-top", totalmarg );
    }

$(".contentbox:nth-child(" + i + ")").css("z-index", z );    

z = z - 1;

i++;

};

Upvotes: 1

Related Questions