Home > Web Front-end > CSS Tutorial > 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?

Mary-Kate Olsen
Release: 2024-12-09 19:15:10
Original
654 people have browsed it

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;
}
Copy after login
<div>
  <a href="#">Anchor Text</a>
</div>
Copy after login

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.

The above is the detailed content of How Can I Change a Parent Container's Background Color Using Only CSS When Hovering Over a Child Element?. 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