问题:fixed元素被另一个fixed元素包含的时候在chrome下fixed子元素的定位会受到父元素的影响。
demo(http://jsbin.com/qumah/1):
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>JS Bin</title> <style> .fixed { position: fixed; left:0; top:20px; width:200px; height:200px; background:#fee; } .fixed-child { width:150px; height:150px; background: #fcc; top:40px; right: 20px; left: auto; z-index: 100; } .absolute { position: absolute; right: 20px; width:100px; height:100px; background:#f11; } </style></head><body> <div class="fixed">fixed position<div class="fixed fixed-child">fixed child position</div></div> <div class="absolute">absolute position</div> </body></html>
IE(IE8-IE11效果一致,IE7没有测试,IE6不支持fixed元素)下效果:
chrome下效果:
Firefox下效果:
Safari下效果:
解释:层叠关系是受层叠上下文影响的。文档中的层叠上下文由满足以下任意一个条件的元素形成:
opacity
属性值小于1. (参考the specification for opacity),transform属性值不为“none”,
mix-blend-mode属性值不为“normal”,
isolation属性值为“isolate”,
position: fixed
总是创建一个新的层叠上下文, 即使z-index的值是"auto" (Seethis post),参考来源:The stacking context - MDN
每个层叠上下文都有如下的层叠级别组成(显示顺序从后到前):
参考来源:RM8015: IE6 IE7 IE8(Q) 中定位元素 'z-index' 为默认值在某些情况下会产生新的层叠上下文
结论:在chrome22+的浏览器中,position为fixed总是会创建新的重叠上下文,所以子fixed元素在此时会以父fixed元素为层叠上下文,子元素的层叠关系会受到父元素的影响。而在非chrome浏览器下子fixed元素并不会创建新的层叠上下文,fixed元素的层叠上下文为最近的层叠上下文。
因此,我们应该尽量避免出现fixed元素相互嵌套的问题。如果必须有嵌套的情况,建议修改fixed父元素的z-index值来修正在chrome下fixed子元素的层叠问题。
题外话:
对于opacity小于1的元素也会产生层叠上下文的问题,可能很多人都不知道。但是规范里面是明文规定的:
Since an element with opacity less than 1 is composited from a single offscreen image, content outside of it cannot be layered in z-order between pieces of content inside of it. For the same reason, implementations must create a new stacking context for any element with opacity less than 1. If an element with opacity less than 1 is not positioned, implementations must paint the layer it creates, within its parent stacking context, at the same stacking order that would be used if it were a positioned element with ‘
z-index: 0
’ and ‘opacity: 1
’. If an element with opacity less than 1 is positioned, the ‘z-index
’ property applies as described in[CSS21], except that ‘auto
’ is treated as ‘0
’ since a new stacking context is always created. Seesection 9.9andAppendix Eof[CSS21]for more information on stacking contexts. The rules in this paragraph do not apply to SVG elements, since SVG has its ownrendering model([SVG11], Chapter 3). ---摘自《CSS Color Module Level 3》
简单来说:
参考文章:
https://developer.mozilla.org/zh-CN/docs/Web/CSS/Understanding_z-index/The_stacking_context
http://www.w3.org/TR/CSS21/visuren.html#z-index
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index
RM8015: IE6 IE7 IE8(Q) 中定位元素 'z-index' 为默认值在某些情况下会产生新的层叠上下文
你需要了解的z-index世界
新闻热点
疑难解答