Make css :hover only affect parent element

心已入冬 提交于 2019-12-01 03:53:05
Litek

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; }

Simply: don't nest your #inner div inside. Little demo: little link. Note that I added:

html, body {
    position: relative;
}

Which is necessary in this case.

Edit: in case you insist on having it nested, a bit of JavaScript is necessary. Here's a sample:

var inn = document.getElementById("inner"), outt = document.getElementById("holder");
outt.onmouseover = function() {
   this.style.backgroundColor = "rgb(0, 162, 232)"; /*I like this color :)*/
}
outt.onmouseout = function() {
   this.style.backgroundColor = "orange";
}
inn.onmouseover = function(ev) {
   ev.stopPropagation();
}

(This would be shorter if written using jQuery, but the idea is the same).

Here's a demo: little link.

PRB

You need to use a bit of JavaScript to stop the event from bubbling. Take a look at this example:

css :hover only affect top div of nest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!