Home > Web Front-end > CSS Tutorial > How Can I Change a Parent Container's Background Color Only When Hovering Over a Child Element Using CSS?

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

Susan Sarandon
Release: 2024-12-30 10:20:11
Original
705 people have browsed it

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

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

While it's generally impossible to target parent elements directly with CSS, there are workaround solutions for specific scenarios. One such scenario is changing the background color of a parent container when hovering over its child element.

Solution: Pointer Events and :hover

This method leverages pointer events and the :hover pseudo-class:

  1. pointer-events: none on parent: This makes the parent element non-interactive, ignoring hover events.
  2. :hover on parent: Define the desired background color change on the parent element when hovered.
  3. pointer-events: auto on child: Re-enable hover events only for the child elements, allowing them to trigger the background color change on the parent.

Compatibility:

  • Works in IE 11 and Edge, Chrome, and Firefox.
  • Note: IE 11 and Edge require the child element to have display: inline-block or display: block for pointer events to work.

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

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