Html 无绝对位置的 Z-Index

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9674988/
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-28 23:04:14  来源:igfitidea点击:

Z-Index without absolute position

htmlcss

提问by GoldenNewby

As a result of CSS trickery like negative margins, occasionally I have some HTML that is rendered below HTML content that occurs later in the HTML document. Even though the original elements should technically be below the later elements, I'd like to display the above the later elements.

由于诸如负边距之类的 CSS 诡计,有时我会在 HTML 文档中稍后出现的 HTML 内容下方呈现一些 HTML。尽管从技术上讲,原始元素应该在后面的元素下方,但我还是想在后面的元素上方显示。

Is it possible to make an HTML element appear above another element without having to specify an absolute position? It doesn't appear that z-index has any effect without an absolute position.

是否可以使 HTML 元素出现在另一个元素之上而不必指定绝对位置?如果没有绝对位置,z-index 似乎没有任何影响。

回答by Phrogz

Yes: use position:relative; z-index:10.

是:使用position:relative; z-index:10

z-indexhas no effect for position:static(the default).

z-indexposition:static(默认)无效。

Note that z-index is not a global layering system, but only differentiates ordering within each positioned parent. If you have:

请注意,z-index 不是全局分层系统,而是仅区分每个定位父级内的排序。如果你有:

<style type="text/css">
  div { position:relative }
  #a  { z-index:1  }
  #a1 { z-index:99 }
  #b  { z-index:2  }
</style>
...
<div id="a"><div id="a1">SUPER TALL</div></div>
<div id="b">I WIN</div>

...then #a1will never render above b, because #bis layered above #a. You can see a demo of this at http://jsfiddle.net/DsTeK

...then#a1永远不会在上面渲染b,因为它#b是分层的#a。你可以在http://jsfiddle.net/DsTeK看到这个演示

回答by Mr Lister

I know Phrogz' answer has been accepted already, and a good answer it is, but just for the record: you don't always need z-index.

我知道 Phrogz 的答案已经被接受,这是一个很好的答案,但只是为了记录:您并不总是需要z-index.

When you have position:relativeon one element, it will also be displayed on top of all other elements that have no position(or position:static). Even if you don't have any z-indexes at all!

当您拥有position:relative一个元素时,它也将显示在所有其他没有position(或position:static)的元素之上。即使您根本没有任何 z 索引!

jsFiddle.

js小提琴