"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Change a Parent Container's Background Color Using Only CSS When Hovering Over a Child Element?

How Can I Change a Parent Container's Background Color Using Only CSS When Hovering Over a Child Element?

Published on 2024-12-22
Browse:274

How Can I Change a Parent Container's Background Color Using Only CSS When Hovering Over a Child Element?

Change Background Color of Parent Container on Child Hover (CSS Only)

While the question about selecting parent elements with CSS is often marked as a duplicate, it overlooks the need for practical solutions. In particular, the issue of changing the background color of a parent container when hovering over its child can be addressed through a CSS-only approach.

Pointer-Events and Hover:

To achieve this effect, we can manipulate pointer events and the :hover pseudo-class:

  1. Set pointer-events: none on the parent. This prevents the parent element from receiving any hover events.
  2. Define the desired parent background color change on hover.
  3. Set pointer-events: auto on the child. This allows the child element to trigger hover events, even though the parent ignores them.

Example:

div {
  height: 200px;
  width: 200px;
  text-align: center;
  pointer-events: none;
}
div:hover {
  background: #F00;
}
div > a {
  pointer-events: auto;
}

This solution effectively captures the hover event on the child element, allowing the parent container's background to change when the child is hovered, all without using JavaScript.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3