Search code examples
javascriptjquerycssz-index

CSS: z-index doesn't work prperly when i append the new div element


I want to implement the website about draw some rectangles and stickers configured by div element.

To add sticker or rectangle, User click the button.

I want to arrange div element in the order of below

(upper) sticker > rack > rectangle > canvas (lower)

So I used z-index in style sheet.

#canvas {
    position: relative;
    z-index: 1;
    ...
}

.rectangle {
    position: absolute !important;
    z-index: 2 !important;
    ...
}

.rack {
    position: absolute !important;
    z-index: 3 !important;
    ...
}

.sticker { 
    position: absolute !important;
    z-index: 4 !important;
    ...
}

It works well, when elements are allocated by html code.

<div id="canvas">
    <div class="rectangle draggable resizable"
        style="left:0px; top:0px; width:200px; height:300px;"
        type="rectangle" id="rectangle_org">

        <div class="rack draggable resizable"
            style ="left: 0; top:40px; width: 50px; height: 100px;"></div>

        <div class="sticker sticker_green draggable"
            type="sticker" id="green"
            style="left:0px; top:0px;">
        </div>

        <div class="sticker sticker_yellow draggable"
            type="sticker" id="yellow"
            style="left:30px; top:0px;"></div>

        <div class="sticker sticker_red draggable"
            type="sticker" id="red"
            style="left:60px; top:0px;">
        </div>

        <div class="sticker sticker_gray draggable"
            type="sticker" id="gray"
            style="left:90px; top:0px;">
        </div>

    </div>
</div>

When I clicked the button to append element to canvas, it doen't work properly.

the new rectangle cover the stickers, even though the z-index of the rectangle is lower than sticker's.

I think the z-index of these are like below

(upper) new sticker > new rack > new rectangle > old sticker > old rack > old rectangle (lower)

How can i fix this error.

Please refer this fiddle (http://jsfiddle.net/crisply/bD35Z/9/)


Solution

  • When you append a new element to the DOM the z-index goes back to 0. I haven't tested this on other browsers, but it happens in Chrome.

    You have to either set z-index manually on the appended element, or code some logic to automatically assign z-index values to your elements.