How to Turn Off a Parent Element\'s Hover Effect When Hovering Over Its Child with Pure CSS?

DDD
Release: 2024-11-03 13:46:31
Original
549 people have browsed it

How to Turn Off a Parent Element's Hover Effect When Hovering Over Its Child with Pure CSS?

Parent Hover Off When Child Hovered: A Pure CSS Approach

In our HTML structure, we have two nested

elements: .parent as the outer container and .child as the inner element. By default, when the mouse cursor hovers over .parent, its background color changes to light blue. However, our goal is to revert the background of .parent to its original gray color when the cursor hovers over .child.

Unfortunately, CSS selectors currently lack the functionality to style a parent element based on its child's state. To circumvent this limitation, we will employ a clever technique using an additional sibling element.

In our CSS, we define the .parent element with its dimensions and padding, and a gray background. When the mouse hovers over .parent, its background turns light blue.

The crucial part is the .child element. We position it a distance above its parent using negative margins (top: -200px;) and give it a dark gray background that transitions to black on hover.

Finally, we introduce the .sibling element. This is a placeholder element, positioned and sized to match .child but located slightly to its left and above it. It also has a colored background that transitions to white on hover.

When the mouse cursor hovers over .child, the .child element transitions its background color to black. Simultaneously, this causes the .sibling element to overlap and cover the portion of .parent that was previously being hovered over. Because .sibling is transparent, the original gray background of .parent becomes visible again.

As a result, when you hover over .child, it turns black and hides the portion of .parent that was previously highlighted. This creates the illusion that the background of .parent has turned back to its original color, even though it's actually still gray behind .sibling.

Despite the limitations of pure CSS in this situation, this technique provides an elegant and effective solution to turning off the hover effect on a parent element when you hover over its child.

The above is the detailed content of How to Turn Off a Parent Element\'s Hover Effect When Hovering Over Its Child with Pure 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template