CSS 为什么 z-index 不适用于 div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9592323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:11:37  来源:igfitidea点击:

Why z-index is not working for div?

csspositioning

提问by TruMan1

I am trying to get my footer to show on top of the footer background, but z-index seems not to be working. Does anyone see what is wrong with it? http://jsfiddle.net/f2ySC/

我试图让我的页脚显示在页脚背景之上,但 z-index 似乎不起作用。有没有人看到它有什么问题?http://jsfiddle.net/f2ySC/

回答by xandercoded

You have to explicitlydefine the positionproperty:

您必须明确定义该position属性:

.footerBox {
    background-color: #FFFFFF;
    border: 10px solid #DDDDDD;
    margin: 10px 0 -200px -10px;
    width: 1185px;
    z-index: 1000;

    position:relative;

}

http://jsfiddle.net/f2ySC/1/

http://jsfiddle.net/f2ySC/1/



This brings the footer into the current stacking context:

这将页脚带入current stacking context

... The root element forms the root stacking context. Other stacking contexts are generated by any positioned element (including relatively positioned elements) having a computed value of 'z-index' other than 'auto'. Stacking contexts are not necessarily related to containing blocks. In future levels of CSS, other properties may introduce stacking contexts, for example 'opacity' ...

... 根元素形成根堆叠上下文。其他堆叠上下文由具有除 'auto' 以外的计算值 'z-index' 的任何定位元素(包括相对定位元素)生成。堆叠上下文不一定与包含块相关。在 CSS 的未来级别中,其他属性可能会引入堆叠上下文,例如 'opacity' ...

http://www.w3.org/TR/CSS2/visuren.html#z-index

http://www.w3.org/TR/CSS2/visuren.html#z-index

回答by Sel Fish

using negative margin is not a good practice. z-index:-1; works it just display the content on the background of another div :)

使用负边距不是一个好习惯。z-索引:-1;工作它只是在另一个div的背景上显示内容:)

回答by PatrikAkerstrand

Is this the effect you are looking for? Updated example

这是您要找的效果吗?更新示例

I added position: relative;to #footerBackand .footerBoxto enable z-index

我添加position: relative;#footerBack.footerBox启用z-index

回答by Hymantheripper

On footerBox set the positionattribute to absoluteYour new code should read as follows

在footerBox 上将position属性设置为absolute您的新代码应如下所示

.footerBox {
    background-color: #FFFFFF;
    border: 10px solid #DDDDDD;
    margin: 10px 0 -200px -10px;
    width: 1185px;
    z-index: 1000;
    position: absolute;
}

See a demo here

在此处查看演示

Using position: relativealso works

使用position: relative也有效