CSS 当 z-index 不起作用时如何强制一个元素到顶部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18039110/
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
how to force an element to the top when z-index is not working?
提问by camino
I am writing a chrome extension which using injection to modify the element in target webpage. I want to show a message bubble when cursor move on an element. But I encounter a problem that sometimes the message bubble is hidden by some other elements. I found that it was because z-index will not work if an element B sits on top of element A, a child element of element A(message bubble) can never be higher than element B.
我正在编写一个 chrome 扩展,它使用注入来修改目标网页中的元素。当光标在元素上移动时,我想显示一个消息气泡。但是我遇到一个问题,有时消息气泡被其他一些元素隐藏。我发现这是因为如果元素 B 位于元素 A 的顶部,则 z-index 将不起作用,元素 A(消息气泡)的子元素永远不会高于元素 B。
To demonstrate it,Here is an example. That obj2 will always be hidden by obj3, although obj2's z-index is 1000000.
为了演示它,这是一个例子。尽管 obj2 的 z-index 为 1000000,但 obj2 将始终被 obj3 隐藏。
Is there any solutions for it?
有什么解决办法吗?
.aaa{
background-color:blue;
width:100px;
height:100px;
}
.ccc{
background-color:red;
width:80px;
height:80px;
z-index:1000000;
}
.bbb{
background-color:green;
position:relative;
top:-50px;
left:50px;
width:100px;
height:100px;
}
<div>
<section id=obj1 class="aaa">
<article id=obj2 class="ccc">
</article>
</section>
</div>
<section id=obj3 class="bbb">
</section>
回答by Feisty Mango
z-index is only applied when the container is also marked as position: relative/absolute. If you change your ccc
rule to the following it will work correctly:
z-index 仅在容器也被标记为 position:relative/absolute 时应用。如果您将ccc
规则更改为以下内容,它将正常工作:
.ccc{
position: relative;
background-color:red;
width:80px;
height:80px;
z-index:1000000;
}