我有一个默认定位的div(即位置:静态)和一个固定位置的div。
如果我设置元素的z索引,似乎不可能让固定元素走到静态元素后面。
在{#
宽度:600 px;
z - index: 10;
}
#{下
位置:固定;
上图:5 px;
宽度:420 px;
左:20 px;
边框:1px实体;
高度:10%;
背景:# fff;
z - index: 1;
}
< div id = " / " >
喂喂喂喂喂喂喂喂喂喂喂喂喂喂喂喂喂喂喂喂喂
< / div >
< div id = "下" > < / div >
或者登录jsfiddle: http://jsfiddle.net/mhFxf/
我可以通过使用
位置:绝对的
在静态元素上,有人能告诉我为什么会这样吗?
(似乎有一个类似的问题,(固定定位打破z指数),但它没有一个满意的答案,因此我在这里问这个与我的示例代码)
这个问题可以用很多方法来解决,但实际上,知道叠加规则可以让你找到最适合你的答案。
解决方案
<html>元素是唯一的堆叠上下文,所以只要遵循堆叠上下文中的堆叠规则,您就会看到元素按此顺序堆叠
The stacking context’s root element (the <html> element in this case)
Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
Non-positioned elements (ordered by appearance in the HTML)
Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
所以你可以
设置z-index为-1,对于#未定位-ve z-index出现在未定位的#over元素后面
将#over的位置设置为相对,以便规则5适用于它
真正的问题
在尝试更改元素的堆叠顺序之前,开发人员应该了解以下内容。
当形成堆叠上下文时
默认情况下,<html>元素是根元素,是第一个堆叠上下文
堆叠上下文中的堆叠顺序
下面的堆叠顺序和堆叠上下文规则来自此链接
当形成堆叠上下文时
When an element is the root element of a document (the <html> element)
When an element has a position value other than static and a z-index value other than auto
When an element has an opacity value less than 1
Several newer CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged media, and possibly others. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context
As a general rule, it seems that if a CSS property requires rendering in an offscreen context, it must create a new stacking context.
堆叠上下文中的堆叠顺序
元素的顺序:
The stacking context’s root element (the <html> element is the only stacking context by default, but any element can be a root element for a stacking context, see rules above)
You cannot put a child element behind a root stacking context element
Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
Non-positioned elements (ordered by appearance in the HTML)
Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)