位置相对和z指数混淆

时间:2013-04-15 17:20:16

标签: html css position z-index relativelayout

的jsfiddle:

JSFiddle of the issue

我在使用相对定位的元素缠绕z-index时遇到了一些麻烦。鉴于这个html,我希望“活动”屏幕组件位于其他两个屏幕之前(是的,我知道这个视觉效果在这个例子中看起来并不好......我已经将问题归结为基础知识):< / p>

<div class="parent-container">
    <div class="screen-component">
        Content inside first screen component
    </div>
    <div class="screen-component">
        Content inside second screen component
    </div>
    <div class="screen-component active">
        Content inside active component.. I want this up top
    </div>    
</div>

这个css:

.parent-container {
    position: relative;
}

.screen-component {
    position: relative;
    z-index: 2000;
}

.screen-component.active {
  position: relative;
  z-index: 5000;
}

我想要的效果是任何'screen-component',其中'active'类位于其他类之前;但是现在它们似乎都被赋予了新的行,尽管.active类的z-index高于.screen-component类

2 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:
http://jsfiddle.net/ZCBXA/3/

(背景颜色仅用于演示目的)

.parent-container {
    position: relative;
}

.screen-component {
    position: absolute;
    z-index: 2000;
    top:0px;
    left:0px;
    background-color: #f00;
}

.active {
    z-index: 5000;
    background-color: #0f0;
}

答案 1 :(得分:1)

如果我了解您正在尝试正确执行的操作,则需要position: absolute;而不是position: relative;。然后给div类赋一个顶值,这样所有具有该类的div与顶部的距离相同,并且z-index为-1以隐藏它们。活动类唯一需要的是比其他类更高的z-index。

.parent-container {
    position: relative;
}

.screen-component {
    position: absolute;
    top:0;
    z-index: -1;
}

.screen-component.active {
    z-index: 0;
}