Issue
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too
*:hover {
border-color: red;
}
main,
article,
div {
border: 1px solid lightgrey;
padding: 30px;
}
*:hover {
border-color: red;
}
<main>
<article>
<div>
</div>
</article>
</main>
The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.
Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?
Solution
You can't avoid the parent :hover with pure CSS today. There are quite a few topics on SO discussing this:
How to apply child:hover but not parent:hover
Safari has introduced support for a :has parent selector, and might solve this if other browsers support it as well. But it's still not a viable option today.
You asked if you can achieve this with javascript, and yes you can hack a solution in javascript using mouseenter and mouseleave events, toggling a CSS class.
https://jsfiddle.net/sq1kcwdt/4/
Answered By - jszobody


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.