我对使用 z-index
有点困惑决定堆栈顺序。
我不太明白浏览器如何处理带有 position
的元素属性(property)与没有属性(property)的人一起。
是否有一个一般规则来决定元素的堆栈顺序是否有明确定位的元素?
不同情况的例子值得赞赏。通常来说,一般来说:
<div>
s 有位置设置和没有位置设置。 <div>
s 与 sibling 混在一起 <div>
s 有位置设置和没有位置设置。 最佳答案
CSS 基础知识 z-index
属性(property)
一个简单的概念z-index
属性基于一个简单的概念:具有较高值的元素将位于沿 z 轴具有较低值的元素之前。所以如果你申请 z-index: 1
至 div.box1
, 和 div.box2
有一个 z-index: 0
,然后 div.box1
将覆盖 div.box2
.
就z轴而言,它指的是三维平面上的深度。在您的计算机上,它可以解释为物体离您越来越近的平面。 (了解有关 Cartesian coordinate system 的更多信息。)
来源:Wikipedia
z-index
适用于定位元素
除非您正在处理 flex 元素或网格元素,否则 z-index
属性仅适用于定位元素。这意味着您可以使用 z-index
在带有 position: absolute
的元素上, position: relative
, position: fixed
或 position: sticky
.如果元素有 position: static
(默认值),或其他一些定位方案,如 float
,然后 z-index
不会有任何影响。
如前所述,虽然 z-index
,如 CSS 2.1 中所定义, 仅适用于定位元素, flex items和 grid items即使在 position
时也可以创建堆叠上下文是 static
.
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.5.4. Z-axis Ordering: the
z-index
propertyThe painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.
这是
z-index
的演示处理非定位的 flex 元素:https://jsfiddle.net/m0wddwxs/堆叠上下文
一旦一个元素被定位和一个
z-index
应用时,会创建一个堆叠上下文。(另见:Full list of circumstances where a stacking context is created.)
堆叠上下文是一组规则,用于管理带有
z-index
的定位元素。 ,及其后代。这些规则控制子元素在堆叠顺序中的放置以及属性影响的范围。本质上,堆叠上下文限制了
z-index
元素本身的范围,其子元素不能影响另一个堆叠上下文中元素的堆叠顺序。如果您曾经尝试申请越来越高
z-index
values 只是发现元素永远不会移出前面,您可能试图在不同的堆叠上下文中覆盖元素。Groups of elements with a common parent that move forward or backward together in the stacking order make up what is known as a stacking context. A full understanding of stacking contexts is key to really grasping how z-index and the stacking order work.
Every stacking context has a single HTML element as its root element. When a new stacking context is formed on an element, that stacking context confines all of its child elements to a particular place in the stacking order. That means that if an element is contained in a stacking context at the bottom of the stacking order, there is no way to get it to appear in front of another element in a different stacking context that is higher in the stacking order, even with a z-index of a billion!
堆叠顺序
CSS 在页面上布置元素时遵循堆叠顺序。这些是没有
z-index
时的堆叠规则指定,从最远到最近:如果
z-index
应用属性,修改堆叠顺序:z-index
的定位元素小于 0 z-index
定位的元素大于 0 来源:W3C
底线:一旦您了解了堆叠上下文,
z-index
简单。 例如
z-index
在行动中见:How z-index works!一篇简短但内容丰富的文章解释
z-index
(包括 opacity
如何影响堆叠顺序)参见:What No One Told You About Z-Index有关
z-index
的完整纲要,有很多例子和插图,参见:MDN Understanding CSS z-index
如需深入了解堆叠上下文,请阅读:W3C Elaborate description of Stacking Contexts
关于css - 了解 z-index 堆叠顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513540/