Parent Hover Off When Child Hovered: A Pure CSS Approach
In our HTML structure, we have two nested
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!