Home >Web Front-end >CSS Tutorial >How Can I Change a Parent Container's Background Color on Child Hover Using CSS?

How Can I Change a Parent Container's Background Color on Child Hover Using CSS?

DDD
DDDOriginal
2024-12-08 18:09:11352browse

How Can I Change a Parent Container's Background Color on Child Hover Using CSS?

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:

  1. Set pointer-events: none on the parent div to make it unresponsive to hover events.
  2. Define the background color change for the parent in the parent-div:hover selector.
  3. Set pointer-events: auto on the child element to enable hover event triggering when the child is hovered.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn