下面是一个非常简单的代码示例,展示了这个问题.
<html> <head> <style> .hover { float: right; } .hover:hover { background-color: blue; } .blocker { opacity: 0.5; } </style> </head> <body> <div class="hover">hover</div> <div class="blocker">blocker</div> </body> </html>
我有一个div A,漂浮在另一个div B上,不透明度为0.5.而且我想添加一个CSS悬浮规则到浮动div.但是由于某种原因我不能.
我是左右浮动,无关紧要.
但是,当我将不透明度改为1时,悬停规则突然发挥作用.
有人可以解释这个行为吗?
我可以通过在一个跨度中包装阻止程序div的内容来“修复”这个问题,但是我觉得我不应该这样做.
这是一个jsFiddle,演示了这个问题:http://jsfiddle.net/ed82z/1/
解决方法
这里的关键词是Stacking Context.
通过将不透明度设置为小于1的值,根据规范,它的分层是不同的,因为它接收到新的堆叠上下文并位于元素下方.
The root element forms the root stacking context. Other stacking contexts are generated by any positioned element (including relatively positioned elements) having a computed value of ‘z-index’ other than ‘auto’. Stacking contexts are not necessarily related to containing blocks. In future levels of CSS,other properties may introduce stacking contexts,for example ‘opacity’ [CSS3COLOR].
来自不透明度
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. See section 9.9 and Appendix E of [CSS21] for more information on stacking contexts. The rules in this paragraph do not apply to SVG elements,since SVG has its own rendering model ([SVG11],Chapter 3).
如何解决它:
您可以将指针事件设置为none,请参阅this fiddle.