简体   繁体   中英

how to move inner div behind surrounding div

My HTML:

<div class="outer">
    <div class="inner">
        Lorem Ipsum
        <div class="innerest">
            <!-- no content -->
        </div>
    </div>
    <div class="inner">
        Lorem Ipsum
        <div class="innerest">
            <!-- no content -->
        </div>
    </div>
</div>

My CSS:

.outer {
    background: red;
    padding: 6px 20px;
    z-index: 10;
    overflow: hidden;
}

.inner {
    background: green;
    z-index: 11;
    float: left;
    margin-left: 12px;
}

.innerest {
    background: blue;
    width: 30px;
    height: 20px;
    z-index: 9;
    position: absolute;
}

Here's a fiddle: http://jsfiddle.net/jsnlry/ycJdy/

I want the blue boxes to be behind the red one. It seems, that z-index is ignored in this case. But why?

Any idea?

In this example z-index only works on the position:absolute element. Try putting a negative value like -9 and it should work.

Do you mean like this:

http://jsfiddle.net/audetwebdesign/WJzRY/

.innerest {
    z-index: -1;
}

Why This Works...

By default, z-index is auto which computes to 0, all elements have the same stacking level.

In my fiddle, I set up a sequence of styles to show what is happening.

You start off with a parent div with two floated children which are out of flow, and the parent height collapses to 12px high because of the padding (Ex 1).

When you declare overflow: hidden , you start a new block formatting context and the floated child elements are retained in the context of the parent, which is why the red background fully covers the child elements (Ex 2).

Finally, you can add absolute positioning to the .innerest elements, and this takes them out of the flow and they project out of the .outer ancestor element. Note that the floated elements affect the computed height of the containing block, unlike absolutely positioned elements. On the right .innerest element, you add z-index: -1 which places this element below all the other elements in the stacking order (computed to 0), so you get the desired effect.

Reference

http://www.w3.org/TR/CSS2/visuren.html#layers

Please add z-index: -1 to innerest class. it will be work.

 .innerest {
 background: blue;
 width: 30px;
 height: 20px;
 z-index: -1;
 position: absolute;

}

尝试将负z-index(-1)添加到.innerest类。

Now used to this code define your .outer class position relative and remove overflow hidden

    .outer {
            background: red;
            padding: 6px 20px;
            position:relative; //add this line 

        }

.outer:after{
content:"";
clear:both;
overflow:hidden;
display:table;
}

    .innerest {
        z-index: -1; // add this line
        position: absolute;
    }

Demo

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