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

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

Mary-Kate Olsen
Release: 2024-12-11 06:27:10
Original
291 people have browsed it

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

Changing Parent Container Background Color on Child Hover with CSS

The question of how to alter the parent element's background color when its child is hovered is common. Typically, this type of question is considered a duplicate of the inquiry regarding whether CSS supports parent selectors.

While it's true that CSS doesn't offer direct parent selectors, there are CSS solutions that can address this specific concern.

Using Pointer Events and :hover

This technique involves three steps:

  1. Apply the pointer-events: none property to the parent element. This will make the parent ignore hover events.
  2. Define the background color change for the parent element on hover: parent:hover { background: #F00; }
  3. Set pointer-events: auto on the child element. This ensures that only the child triggers hover events, thus indirectly affecting the parent.

How it Works:

  • When the child is hovered, the parent is also hovered due to event bubbling.
  • However, the parent's pointer-events: none property prevents it from responding to its own hover pseudo-class.
  • Since the child has pointer-events: auto, it effectively enables event bubbling and triggers the parent's hover.

Example:

div {
  height: 200px;
  width: 200px;
  text-align: center;
  pointer-events: none;
}
div:hover {
  background: #F00;
}
div > a {
  pointer-events: auto;
  display: inline-block;
}
Copy after login
<div>
  <h1>Heading</h1>
  <a href="#">Anchor Text</a>
</div>
Copy after login

This solution is compatible with browsers including IE 11, Edge, Chrome, and Firefox. For IE 11 and Edge, the child element must have display: inline-block or display: block to enable pointer events.

The above is the detailed content of How Can I Change a Parent's Background Color on Child Hover Using CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template