Changing Parent Container Background Color on Child Hover Using CSS
Many may initially suggest that CSS lacks means to target parent elements, but the problem of changing a parent container's background color on child hover can be resolved with a clever solution.
CSS Solution Using pointer-events and :hover
To achieve the desired effect, create three CSS rules:
This approach works because the parent hover event is activated when its child is hovered, while the parent ignores its hover pseudo-class, allowing the hover event to be triggered only on the child.
Example
div { pointer-events: none; } div:hover { background: #F00; } div > a { pointer-events: auto; }
<div> <h1>Heading</h1> <a href="#">Anchor Text</a> </div>
Compatibility
This solution is compatible with IE 11 and Edge, Chrome, and Firefox. However, in IE 11 and Edge, the child element must have display: inline-block or display: block for pointer events to function correctly.
The above is the detailed content of How Can I Change a Parent Container's Background Color on Child Hover Using CSS?. For more information, please follow other related articles on the PHP Chinese website!