Make css :hover only affect parent element

CupOfTea696 picture CupOfTea696 · Sep 29, 2012 · Viewed 24.3k times · Source

In css, how can I stop the :hover event being triggered in a parent element when a child event is hovered, so that it only gets triggered when the parent itself gets hovered? In this case my child element is actually positioned outside it's parent element with absolute positioning, so it's a bit weird when the parent changes when the child gets hovered.

I made a JSFiddle to illustrate the problem.

Here's a JSFiddle of the used solution to my example.

Answer

Litek picture Litek · Sep 29, 2012

There is a pure css solution (even two in fact) but both come at a cost.

  1. You can add pointer-events:none; to your child element - but it will not respond to it's own hover styles either. Pointer-events unfortunately are not supported in IE below version 11 (http://caniuse.com/#search=pointer-events).

  2. Wrap content of your parent element (apart from positioned child) in another one (thats the cost of this method) and apply hover styles to this wrapper.

Examples of both methods here.

.parent-2,
.parent { position:relative; background:#ddd; width:100px; height:100px; }
.parent:hover { background:blue; }
.child { position:absolute; top:0; left:130px; width:100px; height:50px; border:1px solid blue; pointer-events:none; }
/* doesn't work in opera and ie */


.content { position:absolute; top:0; left:0; width:100%; height:100%; z-index:0;}
.content:hover { background:blue; }