Tuesday, April 5, 2011

How can I create many divs on on top of the other using CSS/jQuery?

Basically, I want many(>25) divs to be displayed one on top of the other so that only one can be seen at a time. I have the jQuery UI draggable implemented, so once a div is dragged away, the next div is shown. What CSS do I need to make such a stack of divs? jQuery is also available if required. Thanks!

From stackoverflow
  • You mean something like this?

    #relative_container { position: relative; }
    #relative_container div { position: absolute; top: 0; left: 0; width: 100px; height: 100px; }
    #relative_container div.item_1 { z-index: 100; } /* Higher index means its more on top */
    
    Rohan : Well, that doesn't seem to work.
    Jaanus : This is fine CSS, you should just put the two div-s inside the relative_container.
  • Try this:

    CSS

    div.square {
        cursor: pointer;
        width: 100px;
        height: 100px;
        border: 2px dashed purple;
        position: absolute;
        top: 30px;
        left: 30px;
        font-size: 50px;
        line-height: 100px;
        text-align: center;
        color: white;
    }
    

    jQuery + jQueryUI

    var count = 25;
    
    var colors = ['red','green','blue','orange','yellow'];
    
    while(count--) {
        $('<div/>',{className:'square', text:count}).draggable().css({position:'absolute','z-index':count, text:count, backgroundColor:colors[count % 5]})
                                        .appendTo('body');
    }
    

    EDIT:

    I just noticed that for some reason in IE and Safari .draggable() overrides the absolute positioning with relative, so you need to set it back to absolute after you made it draggable.

    Updated the example above.

    http://jsfiddle.net/p9wWA/

    Brock Adams : Needs: `innerHTML: count`. ;-)
    patrick dw : @Brock - Good point. Updated. :o)
    Brock Adams : @patrick: +1 (Sorry I forgot before.)
    Rohan : Thanks, this is great!
    patrick dw : @Rohan - You're welcome. :o)

0 comments:

Post a Comment