Home >Web Front-end >CSS Tutorial >How to Change a Parent's Background Color on Child Hover with CSS?

How to Change a Parent's Background Color on Child Hover with CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 01:22:10985browse

How to Change a Parent's Background Color on Child Hover with CSS?

Can't Directly Target Parent Elements with CSS

Problem: How to change the background color of the parent container when hovering over the child element using only CSS?

Solution: Using pointer-events and :hover

Compatibility:

  • IE 11 and Edge
  • Chrome
  • Firefox

Steps:

  1. Disable pointer events on the parent div: This ensures that the div ignores :hover events.
div {
  pointer-events: none;
}
  1. Change the parent background on hover: Set the background color to change when the parent is hovered.
div:hover {
  background: #F00;
}
  1. Enable pointer events on the child: This allows the hover event to trigger only when the child is hovered.
div > a {
  pointer-events: auto;
}

Explanation:

When the child element is hovered, the parent div is also hovered because of the pointer-events property. However, the parent's hover pseudo-class is ignored due to the pointer-events: none setting. By enabling pointer events on the child, the hover event triggers solely on the child, causing the parent's background color to change as desired.

Note: In IE 11 and Edge, the child element must have display: inline-block or display: block for pointer events to function properly.

The above is the detailed content of How to Change a Parent's Background Color on Child Hover with 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