Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

css - Can't get z-index to work for div inside of another div

I'm trying to get a drop down menu to work. It consists of an LI with a DIV that appears when the LI is hovered. I want the parent to be drawn in front of the child so that I can create a tabbed effect with the overlapping borders. I can't get the child to be drawn behind the parent.

The following code has the same problem:

<div id="test_1">
    Test 1
    <div id="test_2">
        Test 2
    </div>
</div>

And the CSS

#test_1 {
    border:1px solid green;
    width:200px;
    height:200px;
    background-color:#fff;
    position:relative;
    z-index:999;
}

#test_2{
    border:1px solid red;
    width:200px;
    height:200px;
    background-color:#fff;
    position:relative;
    top:-10px;
    left:-10px;
    z-index:900;
}

The above code will draw test_2 in FRONT of test_1. I want test_2 to be drawn BEHIND test_1. How can I get it to do that? Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A positioned container always contains its children. You can't have the content of a container below the container itself. See this test file that I made (about 7 years ago) showing the situation.

Note in particular that the dark blue div is z-index:-100, but doesn't appear below its z-index:3 parent container, nor below a different z-index:2 container that is its "uncle" (sibling of its parent).

The z-index of an element is only valid with respect to other elements using the same positioned container. Once you set position:relative on test_1 you are causing its z-index to be in a different world than the z-index of test_2. The closest you can do is set #test_2 { z-index:-1 } to cause it to appear below the content of #test_1 (but not below its background).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...